简体   繁体   中英

setContentView() returns null if raw resource folder is not empty

I have a main activity that starts a child activity. In the childs onCreate() I call:

setContentView(R.layout.console);
TextView tv = (TextView)findViewById(R.id.console);

This works find as long as my raw resource folder is empty. When I put any file into it, findViewById() returns null . I cannot find out why there is an interference between files in the raw folder and the lack to find a layout resource.

I tried to build with NetBeans and Eclipse and the R.java contains all necessary entries and no ID clash. If I add a file in the raw folder, the file ID is added correctly in the R.java and nothing else changes.

In LogCat I get a null pointer exception as soon as I try to use the TextView tv. When I write the value of tv to the log immediately after its declaration/initialization, tv is the null reference.

@Override
protected void onCreate(Bundle savedInstanceState)
{
  Log.i("Calling onCreate()");
  super.onCreate(savedInstanceState);
  setContentView(R.layout.console);
  TextView tv = (TextView)findViewById(R.id.console);
  Log.i("tv = " + tv);
}

It seems to be a problem because the activity is lauched by the MAIN activity with

Intent intent = new Intent(getContext(), ConsoleActivity.class);
int requestCode = Activity.RESULT_OK;
startActivityForResult(intent, requestCode);

The layout file console.xml of the console activity is the following:

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

  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

   <ScrollView
    android:id="@+id/scroller"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

        <TextView
         android:id="@+id/console"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"/>
    </ScrollView>

   </LinearLayout>

</LinearLayout>

I found a workaround. The code was part of a library. In the library project, I did not include the raw resource directory, because I do not use raw resources in the library. Now I created a raw directory with some (dummy) files in the library project, and... the null pointer error when adding a raw directory with files in the apps project disappeared miraculousely.

Thanks anyway for your help that stimulated me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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