2

I am developing an App which uses the following code. It is generating an unexpected error as "Attempt to invoke virtual method on a null object reference". I do not understand the reason why this is happening. The error is thrown as the line containing t[i].setTestname(getData(exams[i]));. Could someone please point out what I am doing wrong. Could use some help over here.

void processTestPerformance()
{
    String exams[],rawdata;
    rawdata=data.toString();
    int numberoftests=getNumbers("tabletitle03",rawdata);
    Tests[] t= new Tests[numberoftests];
    exams=new String[numberoftests];
    rawdata=rawdata+"tabletitle03";
    for(int i=0;i<numberoftests;i++)
    {
        int j=rawdata.indexOf("tabletitle03");
        int k=(rawdata.substring(j+1)).indexOf("tabletitle03");
        exams[i]=rawdata.substring(j,j+1+k);
        t[i].setTestname(getData(exams[i]));
        rawdata=rawdata.substring(k);
    }
}

The code for class Tests is as follows:

public class Tests
{
    public int numberofsubjects;
    public String testname;
    public Subject s[];
    public void setS(Subject[] s)
    {
        this.s = s;
    }
    public void setNumberofsubjects(int numberofsubjects)
    {
        this.numberofsubjects = numberofsubjects;
        s=new Subject[numberofsubjects];
    }
    public void setTestname(String testname)
    {
        this.testname = testname;
    }
}

Thanks in Advance.

Abhinav Upadhyay
  • 140
  • 1
  • 14

2 Answers2

1

You create an empty array of Tests class, of size numberoftests

If you look inside that array you will find a sequence of null. Because you never initialize it.

You just need to populate the array so that t[i] will return an instance of your class.

In your for-cycle you can for example use the default constructor:

t[i] = new Tests();
// now you can manipulate the object inside the array
t[i].etTestname(getData(exams[i]));
GVillani82
  • 17,196
  • 30
  • 105
  • 172
0
for(int i=0;i<numberoftests;i++)
        t[i]=new Tests();

That solved my problem.

Abhinav Upadhyay
  • 140
  • 1
  • 14