简体   繁体   English

CustomAdapter上的Android Dagger2依赖注入

[英]Android Dagger2 Dependency Injection on CustomAdapter

I learn Dependency Injection using Dagger2 in my android code, I dont have any trouble using it until I try to inject the presenter in my CustomAdapter for ListView, it always return Null Value. 我在我的android代码中使用Dagger2学习了依赖注入,在尝试将Presenter注入到ListView的CustomAdapter中之前,使用它没有任何麻烦,它始终返回Null值。 The purpose is I want to execute the Presenter function when someone click the ListView Item. 目的是当有人单击ListView Item时我想执行Presenter函数。 This is my CustomAdapter Looks like : 这是我的CustomAdapter看起来像:

public class CustomAdapter extends BaseAdapter {

ArrayList<String> contactNameList, listGroup;
Context context;
ArrayList<Bitmap> contactImages;
ArrayList<Integer> listContactId;

private static LayoutInflater inflater=null;

@Inject
DetailScreenPresenter detailScreenPresenter;

public CustomAdapter(MainActivity mainActivity, ArrayList<String> contactNameList, ArrayList<Bitmap> contactImages, ArrayList<String> listGroup, ArrayList<Integer> listContactId)
{
    this.contactNameList = contactNameList;
    context = mainActivity;
    this.contactImages = contactImages;
    this.listGroup = listGroup;
    this.listContactId = listContactId;
    inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return contactNameList.size();
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

public static class Holder
{

    public Holder(View view,Context context)
    {
        ButterKnife.bind(this,view);

    }

    @BindView(R.id.txtName)
    TextView tvName;

    @BindView(R.id.txtGroup)
    TextView tvGroup;

    @BindView(R.id.imageProfile)
    ImageView img;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    View rowView;
    rowView = inflater.inflate(R.layout.contact_list, null);
    Holder holder=new Holder(rowView, context);

    holder.tvName.setText(contactNameList.get(position));
    holder.img.setImageBitmap(contactImages.get(position));
    holder.tvGroup.setText(listGroup.get(position));
    rowView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            detailScreenPresenter.loadDetail(listContactId.get(position));
        }
    });
    return rowView;
}
}

and this is the MainActivity that trigger the CustomAdapter 这是触发CustomAdapter的MainActivity

public class MainActivity extends AppCompatActivity implements MainScreenContact.View {

@BindView(R.id.listContact)
ListView listView;

ArrayList<String> listName;
ArrayList<Bitmap> listImage;
ArrayList<String> listGroup;
ArrayList<Integer> listContactId;
HashMap<Integer, Bitmap> tempImageArray;
String[] letter={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};


@Inject
MainScreenPresenter mainPresenter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ButterKnife.bind(this);

    listName = new ArrayList<>();
    listImage = new ArrayList<>();
    tempImageArray = new HashMap<>();
    listGroup = new ArrayList<>();
    listContactId = new ArrayList<>();

    DaggerMainScreenComponent.builder()
            .netComponent(((App) getApplicationContext()).getNetComponent())
            .mainScreenModule(new MainScreenModule(this, new ContactDatabaseHelper(this)))
            .build().inject(this);

    mainPresenter.loadPost();
}


@Override
public void showPosts(List<Post> posts) {

    Collections.sort(posts, new Comparator<Post>() {
        @Override
        public int compare(Post post1, Post post2) {
            String name1=post1.getFirstName()+" "+post1.getLastName();
            String name2=post2.getFirstName()+" "+post2.getLastName();
            return name1.compareToIgnoreCase(name2);
        }
    });

    int indexGroup=0;

    for (int i = 0; i < posts.size(); i++) {

        if(posts.get(i).getProfilePic().contains("http"))
            mainPresenter.loadImage(posts.get(i).getProfilePic(), i);
        else
            mainPresenter.loadImage("http://example.com", i);


        if(Arrays.binarySearch(letter,Character.toString(posts.get(i).getFirstName().charAt(0)).toUpperCase())==-1)
        {
            if(listGroup.size()==0)
                listGroup.add("*");
            else
                listGroup.add(" ");
        }
        else
        {
            if(!listGroup.get(indexGroup).equalsIgnoreCase(Character.toString(posts.get(i).getFirstName().charAt(0)))) {
                listGroup.add(Character.toString(posts.get(i).getFirstName().charAt(0)).toUpperCase());
                indexGroup = i;
            }
            else
                listGroup.add(" ");
        }

        listContactId.add(i, posts.get(i).getId());
        listName.add(i, posts.get(i).getFirstName() + " " + posts.get(i).getLastName());

    }

}


@Override
public void showError(String message) {
    Toast.makeText(getApplicationContext(), "Error" + message, Toast.LENGTH_LONG).show();
}

@Override
public void showComplete() {
    Toast.makeText(getApplicationContext(), "Complete", Toast.LENGTH_LONG).show();
}

@Override
public void setImageProfile(Bitmap profileBmp, int x) {
    tempImageArray.put(x, profileBmp);

    if(tempImageArray.size()==listName.size())
    {

        SortedSet<Integer> keys = new TreeSet<Integer>(tempImageArray.keySet());
        for(Integer key : keys)
        {
            listImage.add(tempImageArray.get(key));
        }

        listView.setAdapter(new CustomAdapter(this, listName, listImage, listGroup, listContactId));
    }

}
}

Please help how to inject the DetailScreenPresenter presenter. 请帮助如何注入DetailScreenPresenter演示者。

Thanks alot 非常感谢

In general, in order to perform injection into any Object, you should explicitly call <some_dagger_component>.inject(<target_object>) . 通常,为了对任何对象执行注入,应显式调用<some_dagger_component>.inject(<target_object>)

In your case, you could do it this way: 在您的情况下,您可以这样做:

CustomAdapter adapter = new CustomAdapter(this, listName, listImage, listGroup, listContactId);

DaggerMainScreenComponent.builder()
            .netComponent(((App) getApplicationContext()).getNetComponent())
            .mainScreenModule(new MainScreenModule(this, new ContactDatabaseHelper(this)))
            .build().inject(adapter);

listView.setAdapter(adapter);

However, what you're trying to do is an abuse of dependency injection framework - you should not perform injection into adapter, but simply pass the required objects to adapter's constructor. 但是,您要尝试的是滥用依赖项注入框架-您不应执行注入适配器的操作,而只是将所需的对象传递给适配器的构造函数。

In this post you can find additional information about dependency injection in Android. 本文中,您可以找到有关Android中依赖项注入的其他信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM