0

I know this is a very simple question for you experts,but please forgive me.Im very new to this android platform.

I tried to display a string in a textview when a button is clicked.

But it is not working.No errors are showing.

Can you please help me with where im going wrong.

Thanks in advace.

Below is the code i wrote:

package com.mycmpny.namebtn;

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

public class NameonbuttonclickActivity extends Activity implements View.OnClickListener {
    Button mybtn;
     TextView txtView;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mybtn= new Button(this);
        mybtn.setOnClickListener(this);
        printmyname();
        setContentView(mybtn);
       // setContentView(R.layout.main);
    }

    public void onClick(View view){
        printmyname();
    }
    private void printmyname(){
        txtView.setText("This is my first app");
    }
}
suji
  • 1,470
  • 6
  • 22
  • 41
  • 1
    You should look in the logcat. There you can read the exception. – rekire Feb 08 '12 at 07:59
  • 2
    Long time since I've worked on Android. Still, I can see you create the Button (mybtn = new Button) but not the TextView. So it should be null. – huelbois Feb 08 '12 at 08:01
  • @hurlbois,.now the button is showing.But when i click on that button the text"This is my first app" is not displaying.Can you please help with me this. – suji Feb 08 '12 at 08:31

2 Answers2

1

I have done some modifications in onCreate().here i am making a textview which you left.Do that and say is it working ?

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mybtn= new Button(this);
        mybtn.setOnClickListener(this);
        txtView=new TextView(this);
      //  printmyname();
LinearLayout ll=new LinearLayOut(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.addView(mybtn);
ll.addView(txtView);
        setContentView(ll);
       // setContentView(R.layout.main);
    }

HTH :)

Android Killer
  • 18,174
  • 13
  • 67
  • 90
  • ,thanks a lot.now the button is showing.But when i click on that button the text"This is my first app" is not displaying.Can you please help me this. – suji Feb 08 '12 at 08:18
1

You have not created a new object of TextView.

txtView = new TextView(this);

Else use findViewById if you've created the text View in your xml files.

txtView = (TextView)findViewById(R.id.TextView1);
Aliaksei Kliuchnikau
  • 13,589
  • 4
  • 59
  • 72
tss
  • 111
  • 1
  • 6