0

I am just taking baby steps in learning Android programming..I am following some tutorials for that and while studying how to implement onKeyListener I am getting an error 'java.lang.RuntimeException: Unable to instantiate activity ComponentInfo java.lang.NullPointerException'. This error is leading to another error 'adt unfortunately app has stopped' while trying to run the app on my phone. Here is the logcat:

05-15 15:55:22.087: D/AndroidRuntime(20672): Shutting down VM
05-15 15:55:22.087: W/dalvikvm(20672): threadid=1: thread exiting with uncaught exception (group=0x41ea1ba8)
05-15 15:55:22.087: E/AndroidRuntime(20672): FATAL EXCEPTION: main
05-15 15:55:22.087: E/AndroidRuntime(20672): Process: com.example.keyboardlistener, PID: 20672
05-15 15:55:22.087: E/AndroidRuntime(20672): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.keyboardlistener/com.example.keyboardlistener.MainActivity}: java.lang.NullPointerException

Thanks all for the replies..Here is my current code:

Activity_Main.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.keyboardlistener.MainActivity"
    tools:ignore="MergeRootFrame" />

Fragment_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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.keyboardlistener.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/TextResults"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hi" />

    <EditText
        android:id="@+id/editTextUserEntry1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/TextResults"
        android:layout_marginTop="58dp"
        android:layout_toRightOf="@+id/TextResults"
        android:ems="10" >

        <requestFocus />
    </EditText>

</RelativeLayout>

Main class: public class MainActivity extends ActionBarActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            
            /*
            if (savedInstanceState == null) {
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.container, new PlaceholderFragment())
                        .commit();
            }*/
            
         
            final EditText ed = (EditText)findViewById(R.id.editTextUserEntry1);
            final TextView tv = (TextView)findViewById(R.id.TextResults);
            
            ed.setOnKeyListener(new OnKeyListener(){

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    if(event.getAction()==KeyEvent.ACTION_DOWN)
    {
    if(keyCode == KeyEvent.KEYCODE_ENTER)
    {
    tv.setText(ed.getText());
    }
    }
    return false;
    }
             
            });
        }


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        /**
         * A placeholder fragment containing a simple view.
         */
        public static class PlaceholderFragment extends Fragment {

            public PlaceholderFragment() {
            }

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

    }
5
  • Thanks all for the replies..I tried removing the savedinstancestate code..but its not helping..here is the modified code from MainActivity.java Commented May 16, 2014 at 16:48
  • Can you put your XML Layout? Commented May 16, 2014 at 17:07
  • Updated the main post with all the code Commented May 16, 2014 at 21:30
  • possible duplicate of Unfortunately MyApp has stopped. How can I solve this? Commented May 16, 2014 at 21:32
  • Check the logcat to see what line causes the NPE. Commented May 16, 2014 at 21:32

3 Answers 3

2
Caused by: java.lang.NullPointerException
    at android.app.Activity.findViewById(Activity.java:1884)
    at com.example.keyboardlistener.MainActivity.<init>(MainActivity.java:18)

You're calling findViewById() too early when initializing MainActivity member variables. The activity doesn't have a Window yet.

Move the initialization to onCreate() after setContentView(). There will be a Window at onCreate() phase (no NPE like this) and assuming the views are in the layout you set with setContentView(), you can actually find something after setContentView(). In case the views are in the fragment layout, move the initialization to fragment onCreateView() instead (See NullPointerException accessing views in onCreate() for more on that.)

Sign up to request clarification or add additional context in comments.

2 Comments

if i move the code to onCreateView in PlaceholderFragment..i am getting an error..'Cannot make a static reference to the non-static method findViewById'
call it on the inflated fragment rootView e.g. rootView.findViewById(...)
0
if (savedInstanceState == null) {
    getSupportFragmentManager().beginTransaction()
            .add(R.id.container, new PlaceholderFragment())
            .commit();
}

It looks like you're using Fragments here, which means that all actions that touch the UI should be done within the Fragment.

calling FragmentManager.beginTransaction() is an asynchronous task, which means by the time it finishes its not guaranteed that the Fragment will have been inflated or not, and so its likely that ed is null, causing ed.setOnKeyListener() to throw a NullPointerException

1 Comment

I have updated the root comment with modified code..its still not working for me
0

quit this code

if (savedInstanceState == null) {
    getSupportFragmentManager().beginTransaction()
            .add(R.id.container, new PlaceholderFragment())
            .commit();
}

Because you are implementing a fragment so, you can find in yout view the gui components in your main layout because your fragment is in top.

1 Comment

I have updated the root comment with modified code..its still not working for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.