androidnullpointerexceptionroboguice

Cannot inject view to custom class with RoboGuice


I started to use RoboGuice within my project. I can easily inject views inside fragments and activites but i have some trouble with cusom views. I got null ptr exception every time.

According to RoboGuice's example i did the same with my custom class:

TestActivity

@ContentView(R.layout.test_layout)
public class TestActivity extends RoboActivity {

    @InjectView(R.id.testView_1) TestView testView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}

TestView

 public class TestView extends LinearLayout {


    @InjectView(R.id.log_in_tab) View logInTab;

    public TestView(Context context) {
        super(context);
        initView();
    }

    public TestView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }


    @Override
    public void onFinishInflate() {
        super.onFinishInflate();

        if (logInTab == null)
            Toast.makeText(getContext(), "Still NULL", Toast.LENGTH_LONG).show();
        else
            Toast.makeText(getContext(), "Ok", Toast.LENGTH_LONG).show();

    }

    public void initView() {

        inflate(getContext(), R.layout.login_view, this);
        RoboGuice.injectMembers(getContext(), this);
    }


}

Login view's xml is in pastebin here.

Test layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <view
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        class="hu.illion.kwindoo.view.test.TestView"
        android:id="@+id/testView_1"/>
</LinearLayout>

Toast always says that logInTab is null.

Please help if you can.


Solution

  • I don't know why there is no code examples of that but when i have to inject custom views i use injectViewMembers.

    Hope this work for you:

    public void initView() {
        inflate(getContext(), R.layout.login_view, this);
        RoboGuice.injectMembers(getContext(), this);
        RoboGuice.getInjector(getContext()).injectViewMembers(this);
    }