-1

I am trying to instantiate and add a view object programmatically

RelativeLayout activityMain = (RelativeLayout)findViewById(R.id.activity_main);
View playControlsPanelMinimized = new View(this);
activityMain.addView(playControlsPanelMinimized);

and I get this error in log cat

Attempt to invoke virtual method 
'void android.widget.RelativeLayout.addView(android.view.View)' 
on a null object reference
at com.example.michael.musicplayer.PlayPanel.onBackPressed(PlayPanel.java:50)

This is onBackPressed() method and line # 50

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

    // some code
    );

RelativeLayout activityMain = (RelativeLayout)findViewById(R.id.activity_main);
View playControlsPanelMinimized = new View(this);
activityMain.addView(playControlsPanelMinimized); // Line # 50

}

This is activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="0dp"
    android:paddingRight="0dp"
    android:paddingTop="0dp"
    android:paddingBottom="0dp"
    tools:context=".MainActivity"
    android:id="@+id/activity_main">

    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        />

    <RelativeLayout
        android:id="@+id/hidden_panel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/listView1">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name" />

    </RelativeLayout>

</RelativeLayout>
the_prole
  • 8,275
  • 16
  • 78
  • 163
  • `Log.d` the `activityMain` – pskink Oct 05 '15 at 06:52
  • What do you mean by that? Thanks – the_prole Oct 05 '15 at 06:53
  • read [this](http://developer.android.com/tools/debugging/debugging-log.html), you should really learn about the besics of app debugging – pskink Oct 05 '15 at 06:54
  • 1
    `R.id.activity_main` is a layout, not a view, hence your `findViewById(R.id.activity_main);` will return null. You must use layout inflate instead. – RyanB Oct 05 '15 at 07:22
  • @RyanB Here is an example of a layout with an ID using findViewByID method. It contradicts what you say, and of what you say I can find no example. http://stackoverflow.com/questions/3204852/android-add-a-textview-to-linear-layout-programmatically – the_prole Oct 05 '15 at 09:08
  • 1
    @the_pole Ok, my bad. If we had inflated the layout, then we can get it using findViewById. – RyanB Oct 05 '15 at 09:27
  • @RyanB I inflated the main acitivity, and I am declaring the view object in this new activity. Is main activity possibly no longer inflated? – the_prole Oct 05 '15 at 09:32
  • 1
    If your layout has been inflated then you should be ok. Did you try to declare mainActivity as class private variable & instantiate it in your onCreate() method instead of in onBackPressed event? – RyanB Oct 05 '15 at 09:45
  • @RyanB I thought activity_main was inflated by default in MainActivity class. Is it not? – the_prole Oct 05 '15 at 09:51
  • 1
    I guess it isn't. I had created a test project & have no problem of adding new element into it on the fly. – RyanB Oct 05 '15 at 09:54
  • @RyanB I added the code in my main activity class, and posted the code at the bottom of my question. Is it correct? – the_prole Oct 05 '15 at 09:57
  • Using ` setContentView(R.layout.activity_main)` in the new view worked to get rid of the error – the_prole Oct 05 '15 at 10:14
  • 1
    I hit no error with the code you posted. New view was successfully added to the main activity – RyanB Oct 05 '15 at 10:15
  • @RyanB It works for me too. The problem was if I start a new activity, the old activity is "deflated". How do I work around this problem? How can I add a view to an old activity programagically? – the_prole Oct 05 '15 at 21:42
  • 1
    Ah, according to your code, looks like you want to do it when user click on back button in another activity right? If yes, consider using onResume() event on main activity instead. – RyanB Oct 06 '15 at 01:47
  • @Ryan That is exactly what I want to do. You sure I have to override onResume? If I do that I see the new view at onCreate which is too early. I think I need to use onRestart according to documentation. OnRestart is used for an activity that is completely hidden. – the_prole Oct 07 '15 at 06:27
  • 1
    Ok, but keep in mind that if your parent activity was closed by finish() method, then onRestart() will never be called. – RyanB Oct 07 '15 at 07:05
  • @RyanB Is finish() related to onDestroy()? I have not called any of those methods. I just started a new activity, and the old activity just went to the activity stack and was no longer visible. Thanks for your help. – the_prole Oct 07 '15 at 09:34

2 Answers2

1

Pls keep in mind that before using findViewById() , the View you want to reference must have been inflatet...either using setContentView() or by manually inflating it with an Inflater. Else you just get a null back so thats why the NPE

Ilja KO
  • 1,272
  • 12
  • 26
  • can you point me a specific link from where i got understanding of why to do so? i really dun understand inflating and its need – SSH Oct 05 '15 at 06:58
  • 1
    https://www.udacity.com/course/viewer#!/c-ud853/l-1395568821/e-1395668601/m-1395668602 – Ilja KO Oct 05 '15 at 06:59
  • udacity explains it good....u must inflate them to register your views and viewcontainer in the viewhierarchy of your activity. If you havent inflatet your activityMain layout(bad name btw) the method doesnt find it simply said. So inflation is needed to create an object from xml and get a reference to it.....or just create your object in code but then you must handle its initialization manually instead of relying on xml attributes...this means more code and more handwork.... – Ilja KO Oct 05 '15 at 07:02
1

'void android.widget.RelativeLayout.addView(android.view.View)' on a null object reference

Check if activityMain is null

Something like

RelativeLayout activityMain = (RelativeLayout)findViewById(R.id.activity_main);
View playControlsPanelMinimized = new View(this);
if(activityMain != null)
    activityMain.addView(playControlsPanelMinimized); // Line # 50

If activityMain is null, maybe you forgot to inflate the view.

In a fragment you can do

@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.name_of_your_fragment, container, false);

    //Some code like
    //rootView.findViewById(...);

    return rootView;
}
ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77
  • So you did not inflate the view. Check the edit with an example. – ThomasThiebaud Oct 05 '15 at 07:03
  • yes but still you get null pointer and it wont do as you want check out my answer and the comment section. to understand inflation and building views from xml is essential for an android dev – Ilja KO Oct 05 '15 at 07:03