Passing object as argument in method. App crashes. Why?

A

AC Question

I am pretty new to android develop and java.
I am currently following android tutorials from udacity and a certain lesson asks me to write a method (in MainActivity.java) that checks wherever a checkbox **is checked or **not.

Next lesson asks me to check for another checkbox.

Instead of making another method specifically for any other check box, I tried making one method that has a checkbox object as parameter and that could check any checkbox that I have if is checked/not.

I first declared globally some checkboxes with findViewById method.

Next I built a method that checks if the passed in checkbox is checked or not.
When I run it, the app crashes.

I rebuilt the code in a simple hello world app to simplify the reading. I used instead of checkboxes textviews and applied same thinking. This is the code:

package com.example.android.apptest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
// here I declared globally 2 text view objects
// using cast and findViewById reffered to the xml page
TextView text_view1 = (TextView) findViewById(R.id.textview1);
TextView text_view2 = (TextView) findViewById(R.id.textview2);

@override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

modifyText(text_view1);
}

public void modifyText(TextView text_view) // simple method that changes text
{
text_view.setText("Text has changed");
}
}

Now I am aware I might be doing a huge logical mistake and I am sorry if this question is dumb.
But why the app still crashes?

Am I not allowed to take in objects as parameters in methods?

Am I not allowed to declare globally TextView or CheckBoxes etc objects?
 

FSP Devs

Member
Sep 1, 2017
11
0
0
Visit site
Declare textViews globally:

Code:
private TextView textView1; 
private TextView textView2;

Initialize fields in "onCreate" method:

Code:
textView1 = (TextView) findViewById(R.id.textview1); 
textView2 = (TextView) findViewById(R.id.textview2);
 

Forum statistics

Threads
943,594
Messages
6,919,450
Members
3,159,122
Latest member
rabruslik