0

I just want to display text by clicking on a button, but I have no idea why I'm getting null pointer exception. Why View can not find ids in my case any idea?

public class MainActivity extends Activity {


// Button button;
TextView tv;


protected void onCreate(Bundle savedInstanceState) {

    Random random = new Random(100);
    //     View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    Button button = (Button) findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            tv = (TextView) findViewById(R.id.textView);
            tv.setText("change");
        }
    });
    //      tv=(TextView)findViewById(R.id.textView);


    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
  }
}

I have declared all ids in activity_main.xml properly, but it is giving null pointer in a result:

<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="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Press"
        android:id="@+id/but"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:layout_above="@+id/but"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:text="100" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="press me"
        android:id="@+id/button"
        android:layout_above="@+id/but"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

It is giving the following error:

 Process: com.example.admins.assignment1, PID: 23476
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.admins.assignment1/com.example.admins.assignment1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)



enter code here
Tamir Abutbul
  • 6,472
  • 7
  • 16
  • 44
Falconx
  • 269
  • 2
  • 4
  • 11

2 Answers2

4

You have to set view before call any method so move this:

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Up on top of onCreate() like this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Random random = new Random(100);
    Button button = (Button) findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            tv = (TextView) findViewById(R.id.textView);
            tv.setText("change");
        }
    });
}
James McCracken
  • 14,210
  • 4
  • 49
  • 59
Michele Lacorte
  • 4,546
  • 5
  • 28
  • 52
  • 1
    Why when you create new project in android studio these lines of codes super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);appear in the bottom? As I remember when I worked in eclipse they appeared properly. Thanks for answers! – Falconx Oct 12 '15 at 22:49
  • You're welcome , look here if you have any doubt: http://developer.android.com/training/basics/activity-lifecycle/starting.html – Michele Lacorte Oct 12 '15 at 22:50
0
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random random = new Random(100);
//     View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
Button button = (Button) findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {

    public void onClick(View view) {
        tv = (TextView) findViewById(R.id.textView);
        tv.setText("change");
    } 
}); }
Osama Aftab
  • 836
  • 8
  • 14