0

Hi testing a sample gcm application but everytime i send a message i cant add another value in listview. What happens is the previous message is being replaced by the new one.

Here is my code:

Sorry for poor coding.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_memo);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    list1 = (ListView)findViewById(R.id.listView1);

    registerReceiver(HandleMemoReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));

}
private final BroadcastReceiver HandleMemoReceiver = new BroadcastReceiver(){

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
        //memo.append(newMessage + "\n");
        ArrayList<String> nm = new ArrayList<String>();

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(Memo.this,  android.R.layout.simple_list_item_1,nm);
        list1.setAdapter(adapter);
        adapter.add(newMessage);
        adapter.notifyDataSetChanged();
    }
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.memo, menu);
    return true;
}
public void onBackPressed() {
    finish();//go back to the previous Activity
    overridePendingTransition(R.anim.pull_in_left, R.anim.push_out_right);
}
0

1 Answer 1

2

You need to make your ArrayAdapter a class level variable - at this time, it is reinitialized every time the onReceive() method is fired which causes it to reset to an empty ArrayAdapter and then add in the new message.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.