Question

I'm trying to use droidParts, specifically the DI part. I'm testing 2 injections, InjectResource and InjectView, but the second one doesn;t seem to be working.

I have a simple default layout with a textView:

    <TextView
    android:id="@+id/text1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world"
    tools:context=".MainActivity" />

and here's my sample code:

import org.droidparts.annotation.inject.InjectResource;
import org.droidparts.annotation.inject.InjectView;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends org.droidparts.activity.Activity {

@InjectView(R.id.text1) private TextView txtView;
@InjectResource(R.string.app_name) private String appName;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.v("testLog", appName);

    txtView.setText("Test");

}   
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

The InjectResource works properly and logs the String, but when it gets to the setText("Test"); line I get a nullPointerException. Is there anything else that needs to be done to use InjectView?

Was it helpful?

Solution

The content view needs to be set in preInject() as onCreate() is called right after the injection has been performed. And Views can't be found without layout information.

So the code should look like this:

@Override
public void onPreInject() {
    setContentView(R.layout.activity_main);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);     
    txtView.setText("Test");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top