数组列表项替换旧项而不是添加

时间:2017-01-15 22:01:18

标签: android android-intent arraylist

我遇到的问题是,我items上的新ArrayList(在另一个Activity中创建并通过Intent发送到主要活动中)替换旧的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); } 我添加新项目的地方:

private Socket _tcpWorkSocket;
private byte[] _tcpWorkBuffer;
private byte[] _tcpReceiveBuffer;

public void BeginTcpReceive() {
    if (!Connected)
        return;

    _tcpWorkBuffer = new byte[BufferSize]; // 1024
    _tcpWorkSocket.BeginReceive(_tcpWorkBuffer, 0, BufferSize, 0, new AsyncCallback(TcpReadCallback), this);
}

private void TcpReadCallback(IAsyncResult ar) {
    try {
        if (!Connected)
            return;

        int readBytes = _tcpWorkSocket.EndReceive(ar);
        if (readBytes > 0) {
            byte[] buffer = new byte[readBytes];
            Array.Copy(_tcpWorkBuffer, 0, buffer, 0, readBytes);
            if (User != null)
                User.SessionTimerReset();
            Proccess_Buffer(buffer);
        }
        BeginTcpReceive();
    }
    catch(SocketException ex) {
        Close(false);
    }
    catch (Exception ex) {
        Logger.LogError("{0}: {1}\n{2}", ex.GetType(), ex.Message, ex.StackTrace);
        Close(false);
    }
}

private void Proccess_Buffer(byte[] buffer) {
    if (!Receiving) {
        Receiving = true;
        _tcpPacketLength = BitConverter.ToUInt16(buffer, 0);
        _tcpBytesNeeded = _tcpPacketLength;
        _tcpCurIndex = 0;
        _tcpReceiveBuffer = new byte[_tcpPacketLength];
    }
    int origSize = buffer.Length;
    int copyLength = _tcpBytesNeeded;
    if (_tcpBytesNeeded > BufferSize)
        copyLength = BufferSize;
    Array.Copy(buffer, 0, _tcpReceiveBuffer, _tcpCurIndex, copyLength);
    _tcpCurIndex += buffer.Length;
    _tcpBytesNeeded -= buffer.Length;

    if (_tcpBytesNeeded <= 0) {
        Receiving = false;
        ProcessReceiveBuffer(_tcpReceiveBuffer, Protocal.Tcp);
    }

    if (origSize > buffer.Length) {
        // next packet, incase 2 messages are sent in the same packet.
        byte[] nextBuffer = new byte[buffer.Length - origSize ];
        if (nextBuffer.Length > 1) {
            Array.Copy(buffer, origSize , nextBuffer, 0, nextBuffer.Length);
            Proccess_Buffer(nextBuffer);
        }
        else {
            Logger.LogError("Next buffer length split!");
        }
    }
}

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

1 个答案:

答案 0 :(得分:1)

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

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

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

您需要更改以下内容:

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