Reputation: 405
I have a problem with TextView [?], I initialized textview because I want to make it scrollable but I've got an error.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
dc = new DigitalClock(this);
textViewMesssage = new TextView(this);
dc = (DigitalClock) findViewById(R.id.digitalClock1);
textViewMesssage = (TextView) findViewById(R.id.textV);
textViewMesssage.setMovementMethod(new ScrollingMovementMethod());
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
buttonTest = (Button) findViewById(R.id.button_id);
buttonTest.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());
}
});
}
main.xml
<TextView
android:id="@+id/textV"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="MainActivity"
android:layout_gravity="left"
android:scrollbars = "vertical"
/>
<Button
android:id="@+id/button_id"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Hello"
android:layout_gravity="right"
/>
and error
20:36:04.407 18740 XXX.X ERROR AndroidRuntime Caused by: java.lang.NullPointerException 20:36:04.407 18740 XXX.X ERROR AndroidRuntime at XXX.X.MainActivity.onCreate(MainActivity.java:40) 40 line is
textViewMesssage.setMovementMethod(new ScrollingMovementMethod());
I'm using API lvl 8
Upvotes: 1
Views: 640
Reputation: 83517
You create a new text view with
textViewMesssage = new TextView(this);
and then promptly throw it away with
textViewMesssage = (TextView) findViewById(R.id.textV);
which can potentially return null
. In this case it does because at this point in your code, you have not yet call setContentView();
. Remember that you must call setContentView();
before calling findViewById()
. Because of this, I suggest writing setContentView()
as the second line of every onCreate()
method (after super.onCreate()`).
Upvotes: 1
Reputation: 302
why do you need these two lines, delete them check if it works
dc = new DigitalClock(this);
textViewMesssage = new TextView(this);
and add
setContentView(R.layout.main);
Upvotes: 0
Reputation: 49976
Put :
setContentView(R.layout.main);
at the top of onCreate, also this code makes no sense:
dc = new DigitalClock(this);
textViewMesssage = new TextView(this);
dc = (DigitalClock) findViewById(R.id.digitalClock1); //<< overwrites dc, and is not present in layout
Upvotes: 2
Reputation: 4708
setContentView(R.layout.main);
must be called before you try getting any views from the layout XML.
Upvotes: 6