Search code examples
androidlistviewbaseadapter

ListView Adapter setResult() and Finish() error


I want to startActivity for Result by using startActivityForResult() method.Now the activity which get started has a listview with adapter class for it.I had wriiten following Listview Adapter so when user selects any item it should return back to calling activity with selected item name.I cant able to call 2 methods

setResult() and finish() in following code

Adapter Code:

view.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            SharedPreferences prefernces = mContext.getSharedPreferences("MyKey111", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor1 = prefernces.edit();
            editor1.putString("Custname",customerpopulationlist.get(position).getName());
            editor1.putString("let_id", customerpopulationlist.get(position).getLetId());
            editor1.commit();

            Intent intentMessage = new Intent();

            // put the message in Intent
            intentMessage.putExtra("MESSAGE", "hello");
            intentMessage.putExtra("selected_refer", customerpopulationlist.get(position).getLetId());

            setResult(RESULT_OK, intentMessage);
            finish();

        }
    });

Solution

  • you must hold an reference to your activity that created the adapter then set result to that. the thing you are doing is setting the result of OnClickListener object !!

    add an Activity object to your adapter constructor and save it in a local variable in adapter and call it act then call the setResult() of the activtiy like below:

    view.setOnClickListener(new OnClickListener() {
    
        @Override
        public void onClick(View arg0) {
            SharedPreferences prefernces = mContext.getSharedPreferences("MyKey111", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor1 = prefernces.edit();
            editor1.putString("Custname",customerpopulationlist.get(position).getName());
            editor1.putString("let_id", customerpopulationlist.get(position).getLetId());
            editor1.commit();
    
            Intent intentMessage = new Intent();
    
            // put the message in Intent
            intentMessage.putExtra("MESSAGE", "hello");
            intentMessage.putExtra("selected_refer", customerpopulationlist.get(position).getLetId());
    
            //THESE TWO LINES NEED TO BE CHANGED
            act.setResult(RESULT_OK, intentMessage);
            act.finish();
    
        }
    });