如何从我的自定义适配器更新ListView

时间:2018-03-12 16:30:14

标签: java android

我只是想更新我的ListView,但我不能。我不知道是什么。我做错了什么?我想我创建的适配器缺少一些东西来返回我能处理的真正的适配器。

Home.java(MainActivity)

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    MenuItem item = navigation.getMenu().findItem(R.id.navigation_home);
    item.setCheckable(true);
    item.setChecked(true);
    BoxStore boxStore = AppMain.getBoxStore();
    equipamentoBox = boxStore.boxFor(Equipamento.class);
    lancamentoBox = boxStore.boxFor(Lancamento.class);

    loadObjects();

       ////FOCUS HERE/////------------------------------
    List<Equipamento> equipamentos = new ArrayList<>();
    EquipamentoAdapter adapter;adapter = new EquipamentoAdapter(this, equipamentos);
    listEquipamentos = (ListView) findViewById(R.id.listEquipamentos);
    listEquipamentos.setAdapter(adapter);

    registerForContextMenu(listEquipamentos);



}

EquipamentoAdapter.JAVA

public class EquipamentoAdapter extends ArrayAdapter<Equipamento> {
private final Activity context;
private final List<String> idArray = new ArrayList<String>();
private final List<String> qtdArray = new ArrayList<String>();
private final ArrayList<String> nomeArray = new ArrayList<String>();
private List<Equipamento> equipamentos = new ArrayList<>();

public EquipamentoAdapter(Activity context, List<Equipamento> equipamentos) {
    super(context, R.layout.listview_row, equipamentos);
    for (Iterator iterator = equipamentos.iterator(); iterator.hasNext(); ) {
        Equipamento equipamento = (Equipamento) iterator.next();
        this.idArray.add(Integer.toString((int)equipamento.getId()));
        this.qtdArray.add(Integer.toString(equipamento.getQuantidade()));
        this.nomeArray.add(equipamento.getNome());
    }
    this.context = context;
    this.equipamentos = equipamentos;
}

public void callDialogTransaction(Equipamento equipamento) {
    AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
    LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

    View mView = inflater.inflate(R.layout.dialog_lancamento,null);
    TextView title = (TextView) mView.findViewById(R.id.txtTitle);
    final EditText quantidade = (EditText) mView.findViewById(R.id.edtQtd);
    final EditText Observacao = (EditText) mView.findViewById(R.id.edtObs);
    Button addTransaction = (Button) mView.findViewById(R.id.btnAddTranD);
    title.setText(equipamento.getNome());

    addTransaction.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            if(!quantidade.getText().toString().isEmpty()){
                Toast.makeText(getContext(), "Success!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(), "Erro. Fill everything.", Toast.LENGTH_SHORT).show();
            }
        }
    });

    mBuilder.setView(mView);
    AlertDialog dialog = mBuilder.create();
    dialog.show();
}

public View getView(final int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView = inflater.inflate(R.layout.listview_row,null,true);

    //this code gets references to objects in the listview_row.xml file
    TextView txtQtd,txtName;
    txtQtd = (TextView) rowView.findViewById(R.id.txtQtd);
    txtName = (TextView) rowView.findViewById(R.id.txtName);
    final ImageButton btnAddTransaction = (ImageButton) rowView.findViewById(R.id.btnAddTransaction);

    //this code sets the values of the objects to values from the arrays
    txtQtd.setText(qtdArray.get(position));
    txtName.setText(nomeArray.get(position));

    btnAddTransaction.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Equipamento equipamento = equipamentos.get(position);
            callDialogTransaction(equipamento);
            Animation animation = new AlphaAnimation(1.0f,0.8f);
            animation.setDuration(100);
            btnAddTransaction.startAnimation(animation);
        }
    });
    return rowView;
}

}

我读到我可以尝试使用adapter.notifyDataSetChanged();但它不起作用。此外,我尝试在EquipamentoAdapter.java上添加它,并在需要刷新时从我的MainActivity调用,但它也没有用。我不知道为什么。一切似乎都是正确的。

public void refreshData(){
    this.equipamentos.clear();
    for(Equipamento equipamento : equipamentoBox.getAll()){
        this.equipamentos.add(equipamento);
    }

    notifyDataSetChanged();
}

5 个答案:

答案 0 :(得分:1)

我建议进行以下更改:

  1. 直接从getView内的List中引用equipamento对象,以便getView函数成为

    public View getView(final int position, View view, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView = inflater.inflate(R.layout.listview_row,null,true);
    
        //this code gets references to objects in the listview_row.xml file
        TextView txtQtd,txtName;
        txtQtd = (TextView) rowView.findViewById(R.id.txtQtd);
        txtName = (TextView) rowView.findViewById(R.id.txtName);
        final ImageButton btnAddTransaction = (ImageButton) rowView.findViewById(R.id.btnAddTransaction);
    
        //this code sets the values of the objects to values from the arrays
    
        Equipamento equipamento = equipamentos.get(position);
    
        txtQtd.setText(String.valueOf(equipamento.getId()));
        txtName.setText(String.valueOf(equipamento.getQuantidade()));
    
        btnAddTransaction.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Equipamento equipamento = equipamentos.get(position);
            callDialogTransaction(equipamento);
            Animation animation = new AlphaAnimation(1.0f,0.8f);
            animation.setDuration(100);
            btnAddTransaction.startAnimation(animation);
        }
    });
        return rowView;
    

    }

  2. 使用getCount方法

    设置Items计数

    public int getCount(){    return equipamentos.size(); }

  3. 使用这些,调用notifyDataSetChanged();应该更新列表而无需重新初始化适配器。

答案 1 :(得分:0)

您可以做的一件事就是重新打造适配器,试试这个

public void refreshData(){
    this.equipamentos.clear();
    for(Equipamento equipamento : equipamentoBox.getAll()){
        this.equipamentos.add(equipamento);
    }

    EquipamentoAdapter adapter;adapter = new EquipamentoAdapter(this, equipamentos);
    listEquipamentos.setAdapter(adapter);
}

答案 2 :(得分:0)

GUYS,我注意到如果我使用:

                    equipamentos.clear(); //Clear List
                    for(Equipamento equipamento : equipamentoBox.getAll()){
                        equipamentos.add(equipamento); //Populate List
                    }
                    adapter = null;
                    adapter = new EquipamentoAdapter((Activity) Home.this, equipamentos);
                    listEquipamentos.setAdapter(adapter);
                    adapter.notifyDataSetChanged();

它会起作用。但这在性能方面似乎非常错误。我的申请很少,但我不想做出不好的做法。

答案 3 :(得分:0)

创建一个替换数据的方法,并在添加新元素后检查适配器的大小。

将这样的内容添加到适配器:

adapter.getCount();

然后从活动中检查大小:

CASE WHEN Period<='Current Period' then 'include' else '' end as [Period Include Flag]

答案 4 :(得分:0)

由于您的以下逻辑在适配器的构造函数中 -

enter code here
for (Iterator iterator = equipamentos.iterator(); iterator.hasNext(); ) {
   Equipamento equipamento = (Equipamento) iterator.next();
   this.idArray.add(Integer.toString((int)equipamento.getId()));
   this.qtdArray.add(Integer.toString(equipamento.getQuantidade()));
   this.nomeArray.add(equipamento.getNome());
   }

在notifyDataSetChange之后,不调用适配器,所以你可以做两件事 - 1)在@GastónSaillén回答时初始化适配器。 2)将它放在某种方法中并在调用notifydatasetchange之前调用它。