Populated ArrayList throws OutOfBounds Exception - android

My App
I wanted to make a simple game to get started. For that, I generate houses and then later want to display them to the player.
My Problem
When I try to access my ArrayList that should store the classes of my houses I get an Exception (see below). In my debugger, I can see, that the classes get generated properly before I try to access them.
My Code
Houses.java (This is where I generate my Houses on App start and later try to access them)
public class Houses{
ArrayList<Integer> classes = new ArrayList<>();
int[][] NewHouseProps = new int[20][10];
int[][] HouseProps;
public Houses(){
}
public ArrayList<Integer> getClasses()
{
for(int id=0;id<=8;id++){
Log.d("getClasses()","ID: "+id+" CLASSES: "+classes.get(id)); //Exception
}
return classes;
}
public void GenerateHouses(){
Log.d("Generate Houses","!!");
for(int id=0; id<=8; id++){
Random r = new Random();
int h_class, garage = 0, rooms = 0, furn = 0, balkon = 0, pool = 0;
h_class = r.nextInt(4); //Klasse
if(h_class == 0){
rooms = r.nextInt(4)+1;
balkon = r.nextInt(1);
}else if(h_class == 1){
rooms = r.nextInt(3)+3;
garage = r.nextInt(1)+1;
pool = r.nextInt(1);
balkon = r.nextInt(2);
}else if(h_class == 2){
rooms = r.nextInt(3)+2;
garage = r.nextInt(2)+2;
pool = r.nextInt(1);
}else if(h_class == 3){
rooms = r.nextInt(8)+6;
garage = r.nextInt(6)+4;
pool = r.nextInt(1);
balkon = r.nextInt(3);
}
furn = r.nextInt(1);
int price = GenerateHousePrice(id, h_class, garage, rooms, furn, balkon, pool);
NewHouseProps[id][0] = h_class;
NewHouseProps[id][1] = price;
NewHouseProps[id][2] = rooms;
NewHouseProps[id][3] = furn;
NewHouseProps[id][4] = balkon;
NewHouseProps[id][5] = pool;
NewHouseProps[id][6] = garage;
classes.add(h_class);
Log.d("GenerateHouses","ID: "+id+" CLASS: "+h_class);
Log.d("GenerateHouses","CLASSES: "+classes.get(id));
Log.d("GenerateHouses","PROPS: "+NewHouseProps[id][0]);
}
}
public int GenerateHousePrice(int id, int h_class, int garage, int rooms, int furn, int balkon, int pool){
int price = 0, pricep = 0;
Random r = new Random();
if(h_class == 0){
price = r.nextInt(150000)+50000; // 50 - 200 tausend
price += rooms * 7500;
}
else if(h_class == 1){
price = r.nextInt(165000)+85000; //85 - 250 tausend
price += rooms * 12500;
}
else if(h_class == 2){
price = r.nextInt(300000)+100000; //100 - 400 tausnd
price += rooms * 20000;
}
else if(h_class == 3){
price = r.nextInt(800000)+500000; // 500 - 1.3 Mill.
price += rooms * 15000;
}
if(garage > 0){
pricep += price*0.20;
pricep += garage * 500;
}
if(furn == 1){
pricep += price*0.25;
}
if(balkon > 0){
pricep += price*0.1;
pricep += balkon*500;
}
if(pool == 1){
pricep += 20000;
}
price += pricep;
return price;
}
}
BuyHousesActivity (This is where i want to display it, and when i try to get the Classes it crashes)
public class BuyHousesActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buy_houses);
Houses h = new Houses();
ArrayList<Integer> classes = h.getClasses();
for(int id=0;id<=8;id++){
Log.d("OnCreate Classes: ","Classes: "+classes.get(id)); //Exception
}
ViewPager viewPager = findViewById(R.id.vpPager);
viewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager(), classes));
}
protected class MyViewPagerAdapter extends FragmentStatePagerAdapter {
int clicker = 0;
private List<Integer> pclasses;
private ArrayList<Integer> threeclasses;
MyViewPagerAdapter(FragmentManager fm, ArrayList<Integer> classes) {
super(fm);
pclasses = classes;
if(clicker == 0){
for(int id=0;id<=2;id++) {
threeclasses.add(classes.get(id));
}
}else if(clicker == 1){
for(int id=3;id<=5;id++) {
threeclasses.add(classes.get(id));
}
}else if(clicker == 2){
for(int id=6;id<=8;id++){
threeclasses.add(classes.get(id));
}
clicker = 0;
return;
}
clicker++;
return;
}
#Override
public int getCount() {
return pclasses.size()/3;
}
#Override
public Fragment getItem(int position) {
return FragmentBuyHouse.newInstance(threeclasses);
}
}
The Exception ( Lines marked above):
E/AndroidRuntime: FATAL EXCEPTION: main
Process: at.simonic.realtoroffice, PID: 4913
java.lang.RuntimeException: Unable to start activity ComponentInfo{at.simonic.realtoroffice/at.simonic.realtoroffice.BuyHousesActivity}: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at at.simonic.realtoroffice.BuyHousesActivity.onCreate(BuyHousesActivity.java:31)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
I hope u can help me see where my data gets lost along the way and help me understand the problem behind it.

You are not calling GenerateHouses on your Houses class constructor. Check your BuyHousesActivity onCreate. What you are doing is:
Houses h = new Houses(); // This will create an new object
And in the constructor of this object you do nothing:
public Houses(){}
So this object classes parameter will be empty when you access it:
ArrayList<Integer> classes = h.getClasses();
And that is the reason why you are getting the exception.
So the solution is one of these:
Call GenerateHouses in the Houses object constructor
Call GenerateHouses before accessing classes variable

Related

Android Beginner // Why are my Variables all 0 after i should have filled them?

I just edited this post from my original one, because i could narrow the Problem down, but didn´t want to open an extra post for it.
What i Want
I have an Activity in which i generate Data from Houses into an Array. Then on opening another Activity the Data should be used for displaying it.
My Problem
The Data gets generated correctly, and I can see in my Logs that it is generated before i want to access it. At access it still doesn´t show me my Data.
My Code
Houses.java (Where i generate the Houses and use the Answer already given below to try to get my Data)
public class Houses{
int[][] NewHouseProps = new int[20][10];
int[][] HouseProps;
public Houses(){
}
public ArrayList<Integer> getClasses()
{
ArrayList<Integer> classes = new ArrayList<>();
Log.d("Test","ID: "+3+" CLASS: "+NewHouseProps[3][0]);
Log.d("Test","ID: "+4+" CLASS: "+NewHouseProps[4][0]);
for(int id=0 ; id<=8; id++) {
classes.add(NewHouseProps[id][0]);
Log.d("getClasses","Classes: "+NewHouseProps[id][0]);
Log.d("getClasses!!!!!!!!!", "List: "+classes.get(id));
}
return classes;
}
public void GenerateHouses(){
Log.d("Generate Houses","!!");
for(int id=0; id<=8; id++){
Random r = new Random();
int h_class, garage = 0, rooms = 0, furn = 0, balkon = 0, pool = 0;
h_class = r.nextInt(4); //Klasse
if(h_class == 0){
rooms = r.nextInt(4)+1;
balkon = r.nextInt(1);
}else if(h_class == 1){
rooms = r.nextInt(3)+3;
garage = r.nextInt(1)+1;
pool = r.nextInt(1);
balkon = r.nextInt(2);
}else if(h_class == 2){
rooms = r.nextInt(3)+2;
garage = r.nextInt(2)+2;
pool = r.nextInt(1);
}else if(h_class == 3){
rooms = r.nextInt(8)+6;
garage = r.nextInt(6)+4;
pool = r.nextInt(1);
balkon = r.nextInt(3);
}
furn = r.nextInt(1);
int price = GenerateHousePrice(id, h_class, garage, rooms, furn, balkon, pool);
NewHouseProps[id][0] = h_class;
NewHouseProps[id][1] = price;
NewHouseProps[id][2] = rooms;
NewHouseProps[id][3] = furn;
NewHouseProps[id][4] = balkon;
NewHouseProps[id][5] = pool;
NewHouseProps[id][6] = garage;
Log.d("ID: ", Integer.toString(id));
Log.d("CLASS: ",Integer.toString(NewHouseProps[id][0]));
Log.d("PRICE: ", Integer.toString(NewHouseProps[id][1]));
}
}
public int GenerateHousePrice(int id, int h_class, int garage, int rooms, int furn, int balkon, int pool){
int price = 0, pricep = 0;
Random r = new Random();
if(h_class == 0){
price = r.nextInt(150000)+50000; // 50 - 200 tausend
price += rooms * 7500;
}
else if(h_class == 1){
price = r.nextInt(165000)+85000; //85 - 250 tausend
price += rooms * 12500;
}
else if(h_class == 2){
price = r.nextInt(300000)+100000; //100 - 400 tausnd
price += rooms * 20000;
}
else if(h_class == 3){
price = r.nextInt(800000)+500000; // 500 - 1.3 Mill.
price += rooms * 15000;
}
if(garage > 0){
pricep += price*0.20;
pricep += garage * 500;
}
if(furn == 1){
pricep += price*0.25;
}
if(balkon > 0){
pricep += price*0.1;
pricep += balkon*500;
}
if(pool == 1){
pricep += 20000;
}
price += pricep;
return price;
}
BuyHousesActivity.java(Here the Data should be accessed and displayed)
public class BuyHousesActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buy_houses);
Houses h = new Houses();
ArrayList<Integer> classes = h.getClasses();
for(int id=0;id<=8;id++){
Log.d("OnCreate Classes: ","Classes: "+classes.get(id));
}
List<Integer> images = new ArrayList<>();
images.add(R.drawable.apartment);
images.add(R.drawable.townhouse);
images.add(R.drawable.bungalow);
images.add(R.drawable.villa);
ViewPager viewPager = findViewById(R.id.vpPager);
viewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager(), images));
}
protected class MyViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Integer> imageList;
MyViewPagerAdapter(FragmentManager fm, List<Integer> images) {
super(fm);
imageList = images;
}
#Override
public int getCount() {
return imageList.size();
}
#Override
public Fragment getItem(int position) {
return FragmentBuyHouse.newInstance(imageList.get(position));
}
}
My Logs
Those are the Results of my Logs, with them in place like u see above:
Generating
Accessing
I hope you can help me and show me what i got wrong and/or forgot.
This is happening because you are using a empty list. Look.
In your FragmentBuyHouse you call:
BuyHousesActivity bha = new BuyHousesActivity();
List<Integer> classes = bha.classes;
But when you instance new BuyHouseActivity(), it initialize the array, with none data.
Look your class BuyHouseActivity
List<Integer> classes = new ArrayList<>();
In your implemantation, you populate it array classes in method onCreate() that's not called when you instace the class. This is the reason because you have the error on line 46.
You need pass the data by parameter like you make using Bundle.
Solution 2
You can create a static method to return classes:
Change your BuyHousesActivity:
public class BuyHousesActivity extends FragmentActivity {
List<Integer> classes = new ArrayList<>();
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Houses h = new Houses(); //Activity where my Houses get generated
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buy_houses);
Log.d("1. Step", "!!!!!!!!!!!!!!!!!!!!!!");
// for(int id=0; id<=8;id++){
// classes.add(h.NewHouseProps[id][0]);
// Log.d("Klasse: ", Integer.toString(h.NewHouseProps[id][0]));
// }
// Log.d("2. Step", "!!!!!!!!!!!!!!!!!!!!!!");
/*
classes.add(R.drawable.apartment); //Class 0
classes.add(R.drawable.townhouse); //Class 1
classes.add(R.drawable.bungalow); //Class 2
classes.add(R.drawable.villa); //Class 3
*/
mPager = findViewById(R.id.vpPager);
mPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), classes);
mPager.setAdapter(mPagerAdapter);
}
public static ArrayList<Integer> getClasses()
{
Houses h = new Houses();
classes = new ArrayList<>();
for(int id=0 ; id<=8; id++) {
classes.add(h.NewHouseProps[id][0]);
}
return classes;
}
#Override
public void onBackPressed() {
//ViewPager Last Page or Back
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
And you want get classes like your FragmentBuyHouse
public class FragmentBuyHouse extends Fragment {
private int[] imageResId;
private int fragnumber;
BuyHousesActivity bha = new BuyHousesActivity();
List<Integer> classes = bha.getClasses();
...
}

GridView Pops out NullPointerException

The rows are coming in reverse order. It should be Monday then Tuesday then WednesdayI have a gridview which dynamically fetches data of current week(i.e monday to today). I am facing two issues.
1) My gridView elements are not arranged properly.
2) GridView shows data of that day also whose data does not exists. It simply copies all previous row values. I know rearrangement problem is because of resetPosition variable not getting updated. but if i update it, i get NullPointerException. How can i get rid of these problems?
public class ViewTimeTable extends AppCompatActivity {
private ArrayList<String> mondayStrength,tuesdayStrength,wednesdayStrength,thursdayStrength,fridayStrength;
String [] currentWeek;
int resetPosition;
private Date date;
private Map map;
private int position,pos;
private TextView classTextView,sectionTextView,dateTextView;
private String Class,section,today,day;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one_day_layout);
classTextView = (TextView)findViewById(R.id.class_textView);
sectionTextView = (TextView)findViewById(R.id.section_textView);
dateTextView = (TextView)findViewById(R.id.date_textView);
Intent intent = getIntent();
ParseAnalytics.trackAppOpenedInBackground(intent);
mondayStrength = new ArrayList<String>();
tuesdayStrength = new ArrayList<>();
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception ignored) {
}
map = new HashMap();
String[] lectureTimings = {"Lec/Day","I","II","III","IV","V","VI"};
for(int i =0;i<lectureTimings.length;i++){
mondayStrength.add(lectureTimings[i]);
pos = i;
}
System.out.println(position);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Lectures");
GridView mondayRow = (GridView)findViewById(R.id.mon_grid_view);
final GridAdapterChirag mondayAdapter = new GridAdapterChirag(ViewTimeTable.this,R.layout.grid_element, mondayStrength);
mondayRow.setAdapter(mondayAdapter);
System.out.println(position);
currentWeek = getThisWeek();
Class = intent.getStringExtra("Class");
section = intent.getStringExtra("Section");
position = pos+1;
System.out.println(position);
classTextView.append(Class);
sectionTextView.append(section);
resetPosition=position;
String [] day = {"Mon","Tue","Wed","Thu","Fri"};
for(int i=0;i<currentWeek.length;i++) {
mondayStrength.add(position, day[i]);
System.out.print("ResetPosition before loop"+resetPosition);
query.whereEqualTo("Date", currentWeek[i]);
try {
List<ParseObject> objects = query.find();
for (ParseObject object : objects) {
String lid = object.getString("LectureID");
if (lid.substring(7, 9).equals(Class)) {
String m = String.valueOf(lid.charAt(10));
if (m.equals(section)) {
String periodNumber = lid.substring(4, 6);
if (periodNumber.equals("01"))
position += 1;
else if (periodNumber.equals("02"))
position += 2;
else if (periodNumber.equals("03"))
position += 3;
else if (periodNumber.equals("04"))
position += 4;
else if (periodNumber.equals("05"))
position += 5;
else if (periodNumber.equals("06"))
position += 6;
else
position = 100;
map.put(position, object.getString("Strength"));
}
}
System.out.println("ResetPosition"+resetPosition);
System.out.println("Position"+position);
position = resetPosition;
}
System.out.println(map);
for (int k = 1; k <= map.size(); k++) {
mondayStrength.add(resetPosition + k, map.get(resetPosition+k).toString());
}resetPosition+=7;
System.out.println(mondayStrength.size());
//position++;
//mondayAdapter.notifyDataSetChanged();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
//This method simply returns array of dates of current week
private String[] getThisWeek() {
int factor;
ArrayList<String> week = new ArrayList<>();
long oneDay = 86400000;
Calendar calendar = Calendar.getInstance();
long todayInMillis = calendar.getTimeInMillis();
String date;
String todaysDay = new SimpleDateFormat("EEE").format(new Date());
if(todaysDay.equals("Mon"))
factor = 0;
else if(todaysDay.equals("Tue"))
factor = 1;
else if(todaysDay.equals("Wed"))
factor = 2;
else if(todaysDay.equals("Thu"))
factor = 3;
else if(todaysDay.equals("Fri"))
factor = 4;
else if(todaysDay.equals("Sat"))
factor = 5;
else
factor = 6;
for(;factor>=0;factor--){
calendar.setTimeInMillis(todayInMillis-factor*oneDay);
Date d = new Date(calendar.getTimeInMillis());
date = new SimpleDateFormat("dd-MM-yyyy").format(d);
week.add(date);
}
String [] runningWeek = new String[week.size()];
runningWeek = week.toArray(runningWeek);
return runningWeek;
}
LogCat:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tonystark.adminlogin/com.example.tonystark.adminlogin.ViewTimeTable}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.tonystark.adminlogin.ViewTimeTable.onCreate(ViewTimeTable.java:126)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358) 
at android.app.ActivityThread.access$600(ActivityThread.java:156) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:153) 
at android.app.ActivityThread.main(ActivityThread.java:5297) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
at dalvik.system.NativeStart.main(Native Method) 

two array dimensional ArrayIndexOutOfBoundException and NullPointerException

i wrote a code for calculating some weights. they are integer weights.
and i need to save them in every time the button is clicked.
please help me. i cant see why the compiler gives me an error when i try to push the button for the second time. here is my complete code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the exception it throws:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
UPDATEEEEEEEE
i fixed the problem with arrayindexoutofboundexception by changing W[2][] to W[20][]. but in some clicks it gives me this error:
java.lang.NullPointerException
and it's not clear in which clicks. sometimes it's in the second click. or some times it's in fourth click. please help.
W[clicks] = W[clicks - 1];
in above line, you have get error because you have only define size of the array
int W[][] = new int[2][];
so it assigned W[0][] and W[1][] only
When click on second time variable clicks value is 2 then compiler gives ArrayIndexOutOfBoundException
EDITED.............................................................
you have got null value because of your bad logic and not proper way to build two dimensional array. Pls use debug tool to find the actual problem to implement logic and use two dimensional array like below example in java or android:
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
List<Integer> row1 = new ArrayList<Integer>(1);
row1.add(2);
triangle.add(row1);
List<Integer> row2 = new ArrayList<Integer>(2);
row2.add(3);row2.add(4);
triangle.add(row2);
triangle.add(Arrays.asList(6,5,7));
triangle.add(Arrays.asList(4,1,8,3));
System.out.println("Size = "+ triangle.size());
for (int i=0; i<triangle.size();i++)
System.out.println(triangle.get(i));

Creating a Gridview for a word search

I am trying to create a word search using a gridview but I'm unsure how to add rows from a JSONArray, but my app keeps crashing at this point and also at gridView.addView(tableRow);
This is my new puzzle class
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Arrays;
public class NewPuzzleActivity extends Activity implements OnRetrieveHTTPData {
//word search data
String[] rows;
String[] words;
char[] letters;
//variables for the grid creation
int letterID = 0;
int rowID = 0;
//found words by the user
String[] wordsFound;
int[] rowFound;
int[] columnFound;
int[]directionFound;
// objects within the game *miscellaneous properties*
boolean firstLetterSelected = false;
int numOFLettersSelected = 0;
int[] lettersSelected;
int[] rowsSelected;
int[] columnsSelected;
String selectedString = "";
int directionSelected = 0;
int lastLetterSelected = -1;
String date;
GridView gridView;
TextView textView;
Toast toast;
public NewPuzzleActivity(){
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_puzzle);
gridView = (GridView) findViewById(R.id.gridView1);
Intent intent = getIntent();
if(intent.hasExtra("rows")){
// initialize the data
rows = intent.getExtras().getStringArray("rows");
addRows();
stringArrayToCharArray();
fillGrid();
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
}
if(intent.hasExtra("words")){
words = intent.getExtras().getStringArray("words");
wordsFound = new String[words.length];
rowFound = new int[words.length];
columnFound = new int[words.length];
directionFound = new int[words.length];
fillWords();
}
if(intent.hasExtra("date")){
date = intent.getExtras().getString("date");
//textView = (TextView)findViewById(R.id.Title);
//textView.append(date);
}
}
public void letterButonClick(View view){
if(toast != null){
toast.cancel(); // cancel toast message to prevent multiple toast messages
}
TextView textView1 = (TextView) findViewById(view.getId());
textView1.setTextColor(Color.RED);
//works out the column number of the selected letter(s)
columnsSelected[numOFLettersSelected] = (Integer.parseInt(view.getTag().toString())% rows.length);
if(columnsSelected[numOFLettersSelected] == 0) columnsSelected[numOFLettersSelected] = rows.length;
//works out the row number of the selected letter(s)
rowsSelected[numOFLettersSelected] = (Integer.parseInt(view.getTag().toString())/ rows.length)+1;
if(rowsSelected[numOFLettersSelected] == 0) rowsSelected[numOFLettersSelected] = rows.length;
//fixes the last column
if(columnsSelected[numOFLettersSelected] == rows.length) rowsSelected[numOFLettersSelected]-=1;
lettersSelected[numOFLettersSelected] = Integer.parseInt(view.getTag().toString()) + 4999;
Log.i("Selected Column", Integer.toString(columnsSelected[numOFLettersSelected]));
Log.i("Selected Row", Integer.toString(rowsSelected[numOFLettersSelected]));
if(!firstLetterSelected){
firstLetterSelected = true;
//resets the selected string
selectedString = textView1.getText().toString();
numOFLettersSelected = 1;
}else{
//adds letters to selected string
selectedString += textView1.getText().toString();
//compares to the last letter to work out the direction
if(columnsSelected[numOFLettersSelected] +1 == columnsSelected[numOFLettersSelected - 1] &&
rowsSelected[numOFLettersSelected] +1 == rowsSelected[numOFLettersSelected - 1]){
//direction left / down
directionSelected = 0;
Log.i("Direction", "0");
checkWordFound();
}
else if(rowsSelected[numOFLettersSelected]+1 == rowsSelected[numOFLettersSelected-1]&&
columnsSelected[numOFLettersSelected] == columnsSelected[numOFLettersSelected-1]){
//direction is down
directionSelected = 1;
Log.i("Direction", "1");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected] - 1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]+1 == rowsSelected[numOFLettersSelected-1]){
//direction is right-down
directionSelected = 2;
Log.i("Direction", "2");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]+1 == columnsSelected[numOFLettersSelected-1]&&
rowsSelected[numOFLettersSelected] == rowsSelected[numOFLettersSelected-1]){
//direction is left
directionSelected = 3;
Log.i("Direction", "3");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]-1 == columnsSelected[numOFLettersSelected-1]&&
rowsSelected[numOFLettersSelected] == rowsSelected[numOFLettersSelected-1]){
//direction is right
directionSelected = 4;
Log.i("Direction", "4");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]+1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]){
//direction is left-up
directionSelected = 5;
Log.i("Direction", "5");
checkWordFound();
}
else if(rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]&&
columnsSelected[numOFLettersSelected] == columnsSelected[numOFLettersSelected-1]){
//direction is up
directionSelected = 6;
Log.i("Direction", "6");
checkWordFound();
}
else if(columnsSelected[numOFLettersSelected]-1 == columnsSelected[numOFLettersSelected-1] &&
rowsSelected[numOFLettersSelected]-1 == rowsSelected[numOFLettersSelected-1]) {
//direction is right-up
directionSelected = 7;
Log.i("Direction", "7");
checkWordFound();
}else{
// not a letter within/ around the the first letter selected, reset any selected letters
//deselect words and select a new letter to starr again
//selected string reset
selectedString = textView1.getText().toString();
for(int i : lettersSelected){
try{
TextView letters = (TextView)findViewById(i);
letters.setTextColor(Color.BLACK);
i++;
}catch (Exception e){
//break
Toast.makeText(getApplication(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
//variables reset
directionSelected = -1;
numOFLettersSelected = 0;
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
// new letter to be selected
columnsSelected[0] = (Integer.parseInt(view.getTag().toString())% rows.length);
if(columnsSelected[0] == 0) columnsSelected[0] = rows.length;
rowsSelected[0] = (Integer.parseInt(view.getTag().toString()) / rows.length)+1;
if(rowsSelected[0] == 0) rowsSelected[0] = rows.length;
if(columnsSelected[0] == rows.length) rowsSelected[0] -= 1;
lettersSelected[0] = Integer.parseInt(view.getTag().toString()) + 4999;
textView1.setTextColor(Color.RED);
}
numOFLettersSelected++;
Log.i("Selected TEXT", selectedString);
}
lastLetterSelected = Integer.parseInt(view.getTag().toString());
}
private void fillGrid(){
int LetterChars = 0;
for(int i = 0; i < rows.length * rows.length; i++){
if(LetterChars >= rows.length){
rowID--;
LetterChars = 0;
}
addLetter((TableRow)findViewById(rowID+4000+ rows.length-1));
TextView textView1 = (TextView)findViewById(i+5000);
textView1.setText(Character.toString(letters[i]));
LetterChars++;
}
}
private void fillWords(){
for(int i = 1; i < rows.length -1; i++){
String name = "Word"+i;
int id = getResources().getIdentifier(name, "id", getPackageName());
if(id != 0){
TextView textView1 = (TextView)findViewById(id);
try{
textView1.setText(words[i-1]);
}catch(Exception e){
textView1.setText("");
}
}
}
}
private void stringArrayToCharArray(){
char[] chars = new char[rows.length * rows.length];
int i = 0;
//selection of strings
for(int j = 0; j< rows.length; j++){
// selection of letters
for(int k = 0; k < rows.length; k++){
try{
chars[i] = rows[j].charAt(k);
}catch (Exception e){
Log.e("Error", "Error when adding chars");
}
i++;
}
}
letters = chars;
}
private void addLetter(TableRow row){
TextView textView1 = new TextView(this);
textView1.setId(letterID+5000);
textView1.setPadding(3,3,3,3);
textView1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
TableRow.LayoutParams textLayout = new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT);
textLayout.setMargins(10,0,0,10);
textView1.setTextAlignment(textView1.TEXT_ALIGNMENT_CENTER);
textView1.setGravity(Gravity.CENTER);
textView1.setTag(""+(letterID+1));
textView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
letterButonClick(v);
}
});
textView1.setOnDragListener(new View.OnDragListener() {
//draggin selection *To be implemented*
#Override
public boolean onDrag(View v, DragEvent event) {
return false;
}
});
textView1.setLayoutParams(textLayout);
row.addView(textView1);
letterID++;
}
private void addRows(){
for(int i= 0; i < rows.length;i++){
TableRow tableRow = new TableRow(this);
tableRow.setId(i+4000);
gridView.addView(tableRow);
}
}
private void checkWordFound(){
int foundID = 0;
for(String w: words){
if(selectedString.contains(w)){
//word that have been found
Log.i("Word Found", "Found: " + w);
//highlight words that have been found in the word list
for(int i = 1; i < rows.length-1; i++){
String name = "Word"+i;
int id = getResources().getIdentifier(name, "id", getPackageName());
if(id != 0){
TextView textView1 = (TextView)findViewById(id);
try{
if(textView1.getText().equals(w)){
//textview that contains the found words
textView1.setTextColor(Color.GREEN);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
//add to found
wordsFound[foundID] =w;
columnFound[foundID] = columnsSelected[0];
rowFound[foundID] = rowsSelected[0];
directionFound[foundID] = directionSelected;
//variables reset
directionSelected = -1;
numOFLettersSelected = 0;
lettersSelected = new int[rows.length];
rowsSelected = new int[rows.length];
columnsSelected = new int[rows.length];
}
foundID++;
}
checkCompletion();
//no words are found
}
private void checkCompletion(){
if(Arrays.equals(words, wordsFound)){
new AlertDialog.Builder(this)
.setTitle("Word Search Complete")
.setMessage("Submit Score?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//submit score
submitResults();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
}
public void homeClicked(View v){
finish();
}
public void submitResults(){
}
#Override
public void onRetrieveTaskCompleted(String httpData) {
Log.i("Solution Response", responseData);
//debug toasts
Toast.makeText(getApplication(),("Solution Submitted"), Toast.LENGTH_LONG).show();
finish();
}
}
error log
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
05-04 00:49:18.929 6068-6068/sl.lloyd.steve.angrywordsearchthefinalone D/AndroidRuntime﹕ Shutting down VM
05-04 00:49:18.937 6068-6068/sl.lloyd.steve.angrywordsearchthefinalone E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: sl.lloyd.steve.angrywordsearchthefinalone, PID: 6068
java.lang.RuntimeException: Unable to start activity ComponentInfo{sl.lloyd.steve.angrywordsearchthefinalone/sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity}: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
at android.widget.AdapterView.addView(AdapterView.java:461)
at sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity.addRows(NewPuzzleActivity.java:320)
at sl.lloyd.steve.angrywordsearchthefinalone.NewPuzzleActivity.onCreate(NewPuzzleActivity.java:75)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
The problem is you cannot addView(view) directly to GridView, because it is an AdapterView which does not allow that. So you have to do this operation in your Adapter. You just have to add more data to the adapter and after call notifyDataSetChanged() on the adapter, so your GridView will be added the View by itself.

ArrayIndexOutOfBoundsException when parceling set of enums

I can't see the error, I'm having this problem for a long time already... My parcelable class crashes if it is recreated, but I can't find the problem...
I checked the order of writing/reading data.
I checked the functions I use (direct reading/writing vs my custum null save functions)
I marked the line in the first code block that created following exception: java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
SHORT CODE
private Set<ContactType> mMatchesDataLoaded = new HashSet<ContactType>();
saving the set
dest.writeInt(mMatchesDataLoaded.size());
Iterator<ContactType> it = mMatchesDataLoaded.iterator();
while (it.hasNext())
dest.writeInt(it.next().ordinal());
reading the set
int count = source.readInt();
for (int i = 0; i < count; i++)
// ---------------------------------------------------------------------------
// next line produces EXCEPTION!!! java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
// ---------------------------------------------------------------------------
mMatchesDataLoaded.add(ContactType.values()[source.readInt()]);
FULL CODE
I can't see any problems or rather where the problem is...
public class ContactPhone implements Parcelable
{
public static enum ContactType
{
WhatsApp,
Viber,
GooglePlus,
Twitter,
Instagram
}
private boolean mIsUserProfile = false;
private boolean mHasImage;
private int mId;
private long mRawId;
private String mName = null;
private List<PhoneNumber> mNumbers = new ArrayList<PhoneNumber>();
private DBPhoneContact mDBContact = null;
private Set<ContactType> mMatchesDataLoaded = new HashSet<ContactType>();
private HashMap<ContactType, List<BaseMatchContact>> mMatchesData = new HashMap<ContactType, List<BaseMatchContact>>();
// ----------------------
// Parcelable
// ----------------------
#Override
public void writeToParcel(Parcel dest, int flags)
{
ParcelBundleUtils.writeBoolean(dest, mIsUserProfile);
ParcelBundleUtils.writeBoolean(dest, mHasImage);
ParcelBundleUtils.writeIntegerNullSafe(dest, mId);
ParcelBundleUtils.writeLongNullSafe(dest, mRawId);
ParcelBundleUtils.writeStringNullSafe(dest, mName);
dest.writeList(mNumbers);
ParcelBundleUtils.writeLongNullSafe(dest, mDBContact != null ? mDBContact.getId() : null);
// save set
dest.writeInt(mMatchesDataLoaded.size());
Iterator<ContactType> it = mMatchesDataLoaded.iterator();
while (it.hasNext())
dest.writeInt(it.next().ordinal());
// save HashMap
dest.writeInt(mMatchesData.size());
for (Map.Entry<ContactType, List<BaseMatchContact>> entry : mMatchesData.entrySet())
{
dest.writeInt(entry.getKey().ordinal());
dest.writeInt(entry.getValue().size());
for (int i = 0; i < entry.getValue().size(); i++)
dest.writeParcelable(entry.getValue().get(i), 0);
}
}
public void readFromParcel(Parcel source)
{
mIsUserProfile = ParcelBundleUtils.readBoolean(source);
mHasImage = ParcelBundleUtils.readBoolean(source);
mId = ParcelBundleUtils.readIntegerNullSafe(source);
mRawId = ParcelBundleUtils.readLongNullSafe(source);
mName = ParcelBundleUtils.readStringNullSafe(source);
source.readList(mNumbers, PhoneNumber.class.getClassLoader());
Long id = ParcelBundleUtils.readLongNullSafe(source);
mDBContact = null;
if (id != null)
mDBContact = MainApp.getDS().getDBPhoneContactDao().load(id);
// read set
int count = source.readInt();
for (int i = 0; i < count; i++)
// ---------------------------------------------------------------------------
// next line produces EXCEPTION!!! java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
// ---------------------------------------------------------------------------
mMatchesDataLoaded.add(ContactType.values()[source.readInt()]);
// read HashMap
count = source.readInt();
for (int i = 0; i < count; i++)
{
ContactType type = ContactType.values()[source.readInt()];
Class<?> clazz = BaseDef.getMatchClass(type);
// L.d(this, "Classloader: " + clazz.getName() + " type: " + type.name());
int size = source.readInt();
List<BaseMatchContact> list = new ArrayList<BaseMatchContact>();
for (int j = 0; j < size; j++)
list.add((BaseMatchContact) source.readParcelable(clazz.getClassLoader()));
mMatchesData.put(type, list);
}
}
}
The PhoneNumber class implements parcelable and is quite simple and read/writes like following:
#Override
public void writeToParcel(Parcel dest, int flags)
{
ParcelBundleUtils.writeStringNullSafe(dest, mName);
ParcelBundleUtils.writeStringNullSafe(dest, mNormNumber);
ParcelBundleUtils.writeStringNullSafe(dest, mNumber);
}
public void readFromParcel(Parcel source)
{
mName = ParcelBundleUtils.readStringNullSafe(source);
mNormNumber = ParcelBundleUtils.readStringNullSafe(source);
mNumber = ParcelBundleUtils.readStringNullSafe(source);
}
And here are my helper functions:
public static void writeBoolean(Parcel p, boolean b)
{
p.writeByte((byte) (b ? 1 : 0));
}
public static boolean readBoolean(Parcel p)
{
return p.readByte() == 1;
}
public static void writeStringNullSafe(Parcel p, String s)
{
p.writeByte((byte) (s != null ? 1 : 0));
if (s != null)
p.writeString(s);
}
public static void writeIntegerNullSafe(Parcel p, Integer i)
{
p.writeByte((byte) (i != null ? 1 : 0));
if (i != null)
p.writeInt(i);
}
public static void writeLongNullSafe(Parcel p, Long l)
{
p.writeByte((byte) (l != null ? 1 : 0));
if (l != null)
p.writeLong(l);
}
public static void writeDoubleNullSafe(Parcel p, Double d)
{
p.writeByte((byte) (d != null ? 1 : 0));
if (d != null)
p.writeDouble(d);
}
public static void writeParcelableNullSafe(Parcel p, Parcelable d, int flags)
{
p.writeByte((byte) (d != null ? 1 : 0));
if (d != null)
p.writeParcelable(d, flags);
}
public static String readStringNullSafe(Parcel p)
{
boolean isPresent = p.readByte() == 1;
return isPresent ? p.readString() : null;
}
public static Integer readIntegerNullSafe(Parcel p)
{
boolean isPresent = p.readByte() == 1;
return isPresent ? p.readInt() : null;
}
public static Long readLongNullSafe(Parcel p)
{
boolean isPresent = p.readByte() == 1;
return isPresent ? p.readLong() : null;
}
public static Double readDoubleNullSafe(Parcel p)
{
boolean isPresent = p.readByte() == 1;
return isPresent ? p.readDouble() : null;
}
#SuppressWarnings("unchecked")
public static <T extends Parcelable> T readParcelableNullSafe(Parcel p, ClassLoader classLoader)
{
boolean isPresent = p.readByte() == 1;
return isPresent ? (T) p.readParcelable(classLoader) : null;
}
int count = source.readInt(); // index is raised + 1
for (int i = 0; i < count; i++)
mMatchesDataLoaded.add(ContactType.values()[source.readInt()]); // index is raised by 1, starting with 1!
you loop from 0 to 4, but source.readInt() was already called once, so you called it 5 times in total.
ContactType contains 5 values, from index 0 to index 4. You are trying to access the index 5, which does not exist.
mMatchesDataLoaded.add(ContactType.values()[source.readInt()]);
source.readInt() gives you a 5, try to figure out, with debug, why does it contain this value.
My guess is that writeToParcel writes this 5, try to inspect mMatchesDataLoaded which maybe contains some additional unwanted data.

Categories

Resources