android - ListView 适配器 setResult() 和 Finish() 错误

标签 android listview baseadapter

我想通过使用 startActivityForResult() 方法为结果启动Activity。现在启动的 Activity 有一个带有适配器类的 ListView 。我已经编写了以下 ListView 适配器,因此当用户选择任何项目时,它应该返回到调用 Activity 具有所选项目名称。我无法调用 2 个方法

setResult() and finish() in following 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();

        }
    });

最佳答案

您必须保留对创建适配器的 Activity 的引用,然后将结果设置为该 Activity 。您正在做的事情是设置 OnClickListener 对象的结果!!

将 Activity 对象添加到适配器构造函数中,并将其保存在适配器的本地变量中,并调用它 act,然后调用 activtiy 的 setResult() ,如下所示:

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

    }
});

关于android - ListView 适配器 setResult() 和 Finish() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39943058/

相关文章:

android - GCM 注册 SERVICE_NOT_AVAILABLE

android - Android Studio中的同步项目失败

android - 如何在我的 Android Studio 中更改 android\avd 的路径

java - 使页脚不可点击 ListView - Android

android - 无法将页脚添加到 ListView

java - 每行具有不同数量 TextView 的 ListView

android - 从微调器中选择项目时未显示 ListView

android - 为什么我的 Android 应用程序(具有 root 权限)无法访问/开发/输入?

python - 如何在 django CBV(ListView) 中发送 2 个查询集

android - ListView 的项目没有显示