数组列表项替换旧列表项,而不是添加 [英] Array list items replace old ones instead of being added

查看:62
本文介绍了数组列表项替换旧列表项,而不是添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题是,我的 ArrayList 上的新 items 而不是被添加(在另一个Activity中创建并通过Intent发送给Main Activity)替换旧的,所以我总是只显示一个项目.这是我的主要活动:

I have the problem that instead of being added, the new items on my ArrayList (which are created in another Activity and sent to the Main Activity via an Intent) replace the old ones so I always have only one item shown. This is my Main Activity:

public class AssetsOverview extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
protected List<Transaction> myTransactions = new ArrayList<Transaction>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_assets_overview);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fabplus = (FloatingActionButton) findViewById(R.id.fabAdd);
    fabplus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(AssetsOverview.this, AddMoneyTransaction.class));
        }
    });

    FloatingActionButton fabminus = (FloatingActionButton) findViewById(R.id.fabRemove);
    fabminus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(AssetsOverview.this, RemoveMoneyTransaction.class));
        }
    });

    FloatingActionButton fabhint = (FloatingActionButton) findViewById(R.id.fabHint);
    fabhint.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(AssetsOverview.this, HintMoneyTransaction.class));
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    //transaction list

    populateTransactionList();
    populateListView();

    //set a value to the balance variable

    float startBalance = 0;

    //calculate and set current (actual) balance

    TextView balance_view = (TextView) findViewById(R.id.balance_view);
    balance_view.setText(startBalance + " $");

}

//populated transaction list

protected void populateTransactionList() {
    myTransactions.add(new Transaction(78,98,"halo"));
}

//populated list view

private void populateListView() {
    ArrayAdapter<Transaction> adapter = new LastTransactionsListAdapter();
    ListView list = (ListView) findViewById(R.id.last_transactions_listView);
    list.setAdapter(adapter);
}

private class LastTransactionsListAdapter extends ArrayAdapter<Transaction>{
    public LastTransactionsListAdapter(){
        super(AssetsOverview.this, R.layout.transaction_list_view, myTransactions);

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        //make sure there is a view to work with (may null)
        View itemView = convertView;
        if (itemView == null){
        itemView = getLayoutInflater().inflate(R.layout.transaction_list_view, parent, false);
        }

        if(getIntent().getExtras() !=null) {

            Intent depositIntent = getIntent();
            Transaction deposit = depositIntent.getParcelableExtra("data");
            assert false;
            Float newVal = deposit.getValue();
            String newDes = deposit.getDescription();
            Integer newDat = deposit.getTransaction_Date();

            //find a transaction to work with

            Transaction currentTransaction = myTransactions.get(position);

            // fill the view:
            //    value
            TextView valueView = (TextView) itemView.findViewById(R.id.transactionValueView);
            valueView.setText(newVal + "$");

            //    date
            TextView dateView = (TextView) itemView.findViewById(R.id.transactionDateView);
            dateView.setText(newDat + "");

            //    description
            TextView descriptionView = (TextView) itemView.findViewById(R.id.transactionDesciptionView);
            descriptionView.setText(newDes);
        }
        return itemView;
    }
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.assets_overview, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

这是我的 Activity ,在其中添加新项目:

And here is my Activity where I add the new items:

public class AddMoneyTransaction extends AppCompatActivity implements View.OnClickListener {

Button addDepositButton;
EditText depositInput, depositInputDate, depositInputNote;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_money_transaction);

    //setup the Button and EditText

    addDepositButton = (Button)findViewById(R.id.addDepositButton);
    depositInput = (EditText) findViewById(R.id.depositInput);
    depositInputDate = (EditText) findViewById(R.id.depositInputDate);
    depositInputNote = (EditText) findViewById(R.id.depositInputNote);

    //get the onClickListener

    addDepositButton.setOnClickListener(this);

}

@Override
public void onClick(View view) {

    Intent depositIntent = new Intent(AddMoneyTransaction.this, AssetsOverview.class);
    Transaction deposit = new Transaction(100, 16, "random comment");
    deposit.setValue(Float.parseFloat(depositInput.getText().toString()));
    deposit.setTransaction_Date(Integer.parseInt(depositInputDate.getText().toString()));
    deposit.setDescription(depositInputNote.getText().toString());

    depositIntent.putExtra("data",deposit);
    startActivity(depositIntent);
}

我知道很多代码,但是经过数小时的故障排除后,我仍然找不到正确的解决方案.哦,我在Google上什么都没找到...

I kow its a lot of code but after hours of troubleshooting I could not figure out what the correct solution is. Oh and I did not find anything on the google...

推荐答案

问题是您的 getView()方法.您的代码正在执行以下操作:

The problem is your getView() method. What your code is doing is the following:

您使用对具有一个项目的列表的引用创建适配器( new Transaction(78,98,"halo")),这意味着 getView()方法将仅在位置0处调用.

You create the adapter using a reference to a list with one item (new Transaction(78,98,"halo")), which means that the getView() method will be called only for the position 0.

然后,在 getView()内,从意图中获取交易对象,并更改新值的项目值.没有提及要添加的项目.

Then, inside the getView(), you get the transaction object from the intent and change the item values for the new values. There is no mention of items being added.

您需要更改以下内容:

  1. AssetOverview.onCreate()中而不是在适配器内部读取意图
  2. 由于您的列表应在两次活动之间保留,因此您可以将其保存在一个单例中,并在收到意图后添加新项
  3. 每次列表更新时,
  4. 调用 adapter.notifyDatasetChanged()
  5. 您可以通过调用 Transaction current = getItem(position)
  6. 在getView()方法中获取交易
  7. 如果您使用的是单例,请记住在您的 AssetOverview.onDestroy()方法中将其设置为null,以避免内存泄漏.
  1. Read the intent in AssetOverview.onCreate() instead of inside the adapter
  2. Since your list should survive between activities, you may save it in a singleton instance and just add a new item when you receive it from the intent
  3. Call adapter.notifyDatasetChanged() every time the list gets updated
  4. You may get the transaction in the getView() method by calling Transaction current = getItem(position)
  5. If you're using a singleton, remember to set it to null in your AssetOverview.onDestroy() method, to avoid a memory leak.

这篇关于数组列表项替换旧列表项,而不是添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆