Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello everyone, I have a problem that is every time I try to run an android code on the emulator an error message appears and i don't know what to do which is Unfortunately hello has stopped (hello is the name of the application) which consists of a button that when clicked a textview is filled with the world hello. the code used is as follows

Java
package com.example.hello;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    Button btn = (Button) findViewById(R.id.button1);
    TextView tv = (TextView)findViewById(R.id.textView1);
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                tv.setText("Hello Welcome");	
            }
        });
    }
    
    @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;
    }
}


The computer is Pentium Dual core 2GB Ram 1.65 usable 32 bit operating System windows 7 and the emulator is Android 4.4 Api Level 19 512 Ram 16 heap and 200 internal storage
Posted
Updated 6-Apr-14 10:18am
v2
Comments
Peter Leow 6-Apr-14 22:08pm    
You should show your menu xml in your question using the improve question widget.

1 solution

You have to place the btn and tv initialization after the setContentView inside the onCreate
also to add final to the tv as you are using it in an inner class
setContentView(R.layout.activity_main);
		
Button btn = (Button) findViewById(R.id.button1);
final TextView tv = (TextView)findViewById(R.id.textView1);

The End.
 
Share this answer
 
v2
Comments
eng_sammy 7-Apr-14 4:01am    
Thank you very much it worked

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900