【问题标题】:Array list items replace old ones instead of being added数组列表项替换旧项而不是添加
【发布时间】:2017-01-15 22:01:18
【问题描述】:

我的问题是,我的ArrayList 上的新items(在另一个 Activity 中创建并通过 Intent 发送到主 Activity)代替旧的,而不是被添加,所以我总是只有一个显示的项目。这是我的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,我在其中添加了新项目:

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);
}

我知道它有很多代码,但经过数小时的故障排除后,我无法弄清楚正确的解决方案是什么。哦,我在谷歌上没有找到任何东西......

【问题讨论】:

    标签: android android-intent arraylist


    【解决方案1】:

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

    您使用对包含一项 (new Transaction(78,98,"halo")) 的列表的引用来创建适配器,这意味着将仅针对位置 0 调用 getView() 方法。

    然后,在getView() 中,您从意图中获取事务对象,并将项目值更改为新值。没有提到要添加的项目。

    您需要更改以下内容:

    1. AssetOverview.onCreate() 中而不是在适配器内部读取意图
    2. 由于您的列表应该在 Activity 之间保留,您可以将其保存在单例实例中,并在从 Intent 接收到它时添加一个新项目
    3. 每次更新列表时致电adapter.notifyDatasetChanged()
    4. 您可以通过调用Transaction current = getItem(position)在getView()方法中获取事务
    5. 如果您使用的是单例,请记住在您的 AssetOverview.onDestroy() 方法中将其设置为 null,以避免内存泄漏。

    【讨论】:

    • 谢谢,我会尽快尝试。
    • 如果我尝试添加 notifyDatasetChanged 它无法解析方法(它在 populateListView 方法中)
    猜你喜欢
    • 2018-06-21
    • 2016-06-10
    • 2021-08-23
    • 1970-01-01
    • 2020-05-25
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多