-3

I am trying to make an app in Android Studio that would "memorize" my grades and subjects. Currently, I am working on a system that would allow me to make subjects.

Compiled it, got no errors, I open the app, the app crashes and I receive an error: "Attempt to invoke virtual method on a null object reference"

I think the string array has something to do with it.

This is my code:

//these are declared in "public class MainActivity extends AppCompatActivity"
    LinearLayout linearLayout = findViewById(R.id.linearLayout);
    String[] subjectNames;
    int arrayCounter=-1;
    String name;

//addSubject() gets called when a button is pressed
public void addSubject (View view)  {
        EditText editSubjectName = new EditText(this);
        editSubjectName.setHint("Unesi ime predmeta");
        editSubjectName.setSingleLine(true);
        linearLayout.addView(editSubjectName);


        TextView subjectName = new TextView(this);
        subjectName.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        linearLayout.addView(subjectName);

        editSubjectName.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                        (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    name = editSubjectName.getText().toString();
                    arrayCounter++;
                    return true;
                }
                return false;
            }
        });

        subjectNames[arrayCounter] = name;
    }

Thanks in advance!

Okid 62
  • 3
  • 2
  • 1
    It crashes as soon as you launch it? Or when you click the button? Can you provide the important bits of the `Activity` (eg `onCreate`, `onResume`, etc)? Can you provide the stack trace? – gthanop Jan 23 '22 at 15:59

1 Answers1

0

you are not initializing the array, do one of those

String[] subjectNames = new String[10]; // if you are sure you have a maximum of 10 subjects

if you want it to be dynamic, then you can use

List<String> subjectNames = new ArrayList<String>(); //create an arraylist

and then when you want to add an item, you do

subjectNames.add(name);

which will add it to the end of the list.

take a look at this answer for more info https://stackoverflow.com/a/13395230

Jimmar
  • 4,194
  • 2
  • 28
  • 43