Krupa Krupa - 6 months ago 24
Android Question

Fetching list data using Model class in android

I have two the Model class

Speciality
and
SubSpeciality
. when i am calling getsubSpecialityList it returns
NullpointerException
.

Speciality Model

public class Speciality
{
public String name;
public List<SubSpeciality> subSpecialityList;
public String getname()
{
return name;
}
public void setname(String name)
{
this.name = name;
}
public List<SubSpeciality> getsubSpecialityList()
{
return subSpecialityList;
}
public void setsubSpecialityList(List<SubSpeciality> subSpecialityList)
{
this.subSpecialityList = subSpecialityList;
}
}


SubSpeciality Model

public class SubSpeciality
{
public String name;
public String getnamesub()
{
return name;
}
public void setnamesub(String name)
{
this.name = name;
}
}


adding item in both model with below code

List<Speciality> specialityList = new ArrayList<Speciality>();
List<SubSpeciality> subspecialityList = new ArrayList<SubSpeciality>();
Speciality spe = new Speciality();
spe.setname("Othopedic");

SubSpeciality sub= new SubSpeciality();
sub.setnamesub("---Select speciality---");
sub.setnamesub("1");
sub.setnamesub("2");
sub.setnamesub("3");
subspecialityList.add(sub);
spe.setsubSpecialityList(subspecialityList);
specialityList.add(spe);


getting error in below code

for(int j= 0;j<specialityList.size();j++)
{
Toast.makeText(RegisterActivity.this,specialityList.get(j).getsubSpecialityList().get(j).getnamesub()+"hii",Toast.LENGTH_SHORT).show();
}


Logcat output:

FATAL EXCEPTION: main Process: careers.app.com.jobssearch, PID: 29880
java.lang.NullPointerException
at careers.app.com.jobssearch.Activity.RegisterActivity$getSpeciality.onPostExecute(RegisterActivity.java:320)
at careers.app.com.jobssearch.Activity.RegisterActivity$getSpeciality.onPostExecute(RegisterActivity.java:263)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5072)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)

RRR RRR
Answer

Here is the error

specialityList.get(j).getsubSpecialityList().get(j)

You are assuming that both array will be having same size but sometimes it cannot be..

so your code should be

for(int j= 0;j<specialityList.size();j++)
{
    for(int k=0;k<specialityList.get(j).getsubSpecialityList().size();k++)
        Toast.makeText(getActivity(),specialityList.get(j).getsubSpecialityList().get(k).getnamesub()+"hii",Toast.LENGTH_SHORT).show();
}