sdfsdf sdfsdf
sdfsdf sdfsdf

Reputation: 1

Force close error

What is the force close problem of this program?

public class MyActivity extends Activity {

    TextView t=(TextView)findViewById(R.id.textView1); 
    Button r=(Button)findViewById(R.id.button2);
      private OnClickListener i=new OnClickListener(){

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            t.setText("fghffghfhgf");
        }     
      };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        r.setOnClickListener(i);
    }
}

Upvotes: 0

Views: 104

Answers (1)

Alexis C.
Alexis C.

Reputation: 93842

You need to get your TextView and Button after inflating the layout.

public class MyActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //here inflate the layout
        setContentView(R.layout.main);

        //now you can get your widgets
        final TextView t= (TextView)findViewById(R.id.textView1);
        Button r=(Button)findViewById(R.id.button2);
        r.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            t.setText("fghffghfhgf");    
        }

      };
      );
    }
}

I really recommend you to check this to build your first app.

Upvotes: 3

Related Questions