androidlistviewandroid-activityonitemclicklisteneronitemlongclicklistener

Android pass multiple data from list to another activity


I have got:

mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        choosedOffer= mListTest1.get(position).toString();
        return false;
    }
});

and

public void onBackPressed() {
    Intent intent = new Intent(ListviewActivity.this, MainActivity.class);
    intent.putExtra("text",choosedOffer);
    setResult(RESULT_OK, intent);
    finish();
}

in one activity.

The second activity contains:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1) {
            if(resultCode == RESULT_OK){
                String passedText=data.getStringExtra("text");
                ar.add(passedText);
            }
        }

}

Now what I need:

After long click on mListView item, I want to store its position somehow and then, after button "Back" click, I want the position to be passed to ar array in second activity. It works but only for one item from list. If I click another position and then "Back" button, only the last clicked item position will be passed to another activity. Can I pass somehow all items/positions that were clicked before pressing "Back" button (not only the last one)?


Solution

  • Try this:

    ArrayList<String> choosedOffer = new ArrayList<String>();
    
    mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            choosedOffer.add(mListTest1.get(position).toString());
            return false;
        }
    });
    

    and

    public void onBackPressed() {
        Intent intent = new Intent(ListviewActivity.this, MainActivity.class);
        intent.putStringArrayListExtra("text",choosedOffer);
        setResult(RESULT_OK, intent);
        finish();
    }
    

    The second activity

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if(resultCode == RESULT_OK){
                ArrayList<String> passedText = data.getStringArrayListExtra("text");
                ar.addAll(passedText);
            }
        }
    }