Reputation: 714
I'm currently new to Android development and have run into a problem that previous research isn't helping me to solve. I'm using findViewById() in an Android activity to grab a TextView object declared in the activity's corresponding xml fragment file like so:
public void scanLocalApk() {
//get the list of apks in the default downloads directory
ArrayList<File> foundAPKs = findApksInDownloadDirectory();
//display the list of found apks
String apkListString = "";
if (foundAPKs != null)
for (File f : foundAPKs)
apkListString += (f.getName() + "\n");
TextView displayApksTextView = (TextView) findViewById(R.id.display_apks);
displayApksTextView.setText(apkListString);
TextView apkToInstallTextView = (TextView) findViewById(R.id.label_apk_to_install);
apkToInstallTextView.setVisibility(View.VISIBLE);
EditText apkToInstallEditText = (EditText) findViewById(R.id.apk_to_install);
apkToInstallEditText.setVisibility(View.VISIBLE);
}
A NullPointerException is being thrown at this line: displayApksTextView.setText(apkListString); because the findViewById call in the line above it is returning null.
The resource "display_apks" is defined in "fragment_scan_local_apk.xml" here:
<TextView android:id="@+id/display_apks"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Previously mentioned solutions around the web have said to ensure that setContentView() is called above findViewById(), but in my code it is.
Does anyone have any ideas as to what the problem could be?
Edit: As per request, I call setContentView() here
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_local_apk);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
//branch to a logic method
scanLocalApk();
}
Upvotes: 0
Views: 3883
Reputation: 39191
The Views in your Fragment's layout xml are being inflated into the Fragment's View hierarchy, which won't be added to the Activity's hierarchy until the onAttach()
callback, so findViewById()
in the context of the Activity will return null for those Views at the time that onCreate()
is called.
If you want to keep the Views in the Fragment, it would be better to call findViewById()
on the View that is returned from the onCreateView()
method in the Fragment, and move the Views' functionalities and references to the Fragment.
If you don't want/need to use Fragments, you can move the Views in fragment_scan_local_apk.xml
to activity_scan_local_apk.xml
, and keep the rest of the code as it is. If you decide to go with this option, you can remove the code for the PlaceholderFragment
.
Upvotes: 5