Android Invalid index 0, size is 0 [duplicate] - java

This question already has answers here:
IndexOutOfBound Exception throwing Android
(2 answers)
Closed 7 years ago.
I have an error coming up and it's saying it is in this method pointing at the address list. Does anyone has a suggestion why this is happening and the app crashes?
Appreciate it.
01-22 14:03:25.466 2271-2271/? E/AndroidRuntime:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
List<Address> addressList=null;
if (address!=null || !address.equals("")) {
Geocoder geocoder = new Geocoder(getActivity());
try {
addressList = geocoder.getFromLocationName(address, 1);
} catch (IOException e) {
e.printStackTrace();
}
}
if (addressList != null){
Address addresses = addressList.get(0);
// my address lng and lgnt
latLngOffers = new LatLng(addresses.getLatitude(), addresses.getLongitude());
latLocation = addresses.getLatitude();
longLocation = addresses.getLongitude();
// Log.d("Offer address", String.valueOf(latLocation));
}
// latOffer=53.3399009;
// Log.d("my location inside", String.valueOf(latOffer));
DecimalFormat df = new DecimalFormat("##.###");
df.setRoundingMode(RoundingMode.DOWN);
// System.out.println(df.format(latLocation));
Log.d("offer location", String.valueOf(df.format(longLocation)));
Log.d("my location inside", String.valueOf(df.format(longOffer)));
String loffer = df.format(latOffer);
String lonOffer = df.format(longOffer);
String llocation = df.format(latLocation);
String lngLocation = df.format(longLocation);
String lsearch = df.format(latSearch);
String lngsearch = df.format(longSearch);

If there are no elements in a list or array, you can not retrieve the first (non-existing) element.
The valid indices are:
0 -> (number of elements - 1)
If there are no elements, there is no valid index.

Related

I am getting Exception error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 [duplicate]

This question already has answers here:
Java String split removed empty values
(5 answers)
When processing a csv String with an empty final field, myString.split( "," ) returns incorrect number of array entries
(1 answer)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
Please check my code.
I am trying to store information from excel to a object and based on search criteria, I am trying to get the values in console.
public class Assignment3 {
public static void main(String[] args) {
String filePath = "E:\\Java_All\\Assignment\\PreAuthOrig2.csv";
excelRead data = getMemberDetails(filePath, "1001") ;
System.out.println(data.toString());
}
public static excelRead getMemberDetails (String filePath, String MemberID)
{
try
{
BufferedReader br = new BufferedReader (new FileReader (filePath));
String readexcel;
List<excelRead> dataList = new ArrayList <excelRead>();
while ((readexcel = br.readLine()) !=null)
{
excelRead readLines = new excelRead();
String lines[] = readexcel.split(",");
readLines.setMemberID(lines[0]);
//* requirement 2 : if member id is 1002, then update Reviewer name as John and Reviewer status = Pending *\\
if (lines[0] == "1002")
{
readLines.setReviewerName("John");
readLines.setReviewStatus("Pending");
}
else
{
readLines.setReviewerName(lines[6]);
readLines.setReviewStatus(lines[7]);
}
readLines.setMemberName(lines[1]);
try
{
Date date = new SimpleDateFormat("dd-MM-yyyy").parse(lines[2]);
java.sql.Date dateOfBirth = null;
readLines.setDateOfBirth(dateOfBirth);;
Date date1 = new SimpleDateFormat("dd-MM-yyyy").parse(lines[3]);
java.sql.Date dateOfSubmission = null;
readLines.setDateOfSubmission(dateOfSubmission);
}
catch (Exception e)
{
System.out.println("Date Format is wrong");
}
readLines.setProcedureName(lines[4]);
readLines.setPreReviewStatus(lines[5]);
readLines.setReviewerName(lines[6]);
readLines.setReviewStatus(lines[7]);
readLines.setNotificationMailId(lines[8]);
readLines.setTATStatus(lines[9]);
dataList.add(readLines);
}
for (excelRead a : dataList)
{
if (a.getMemberID().equals(MemberID))
{
return a;
}
}
}
catch (IOException e)
{
System.out.printf("IO Exception", e);
}
return null;
}
}
Please find my requirement:
Requirement 1: Provide MemberID and Filpath as input and return member details.
Requirement 2: Update reviewername as John and review status as Pending if MemberID = 1002.
Requirement 3: Set TAT as RED if date of Submission is greater than 10 days from today
Set TAT as AMBER if date of Submission is greater than 5 days from today
Set TAT as green if date of Submission is greater than 1 day from today but less than 5 days.
Requirement 4: get member details if review status is approved.
requirement 5: For TAT status as RED update NotificationMailID.[enter link description here][1] Input Filepath, Notification EnailID.
CSV File:
MemberID,MemberName,dateOfBirth,dateOfSubmission,ProcedureName,PreReviewStatus,ReviewerName,ReviewStatus,NotificationMailId,TATStatus
1001,Avanthika,12-01-1989,07-12-2019,X-Ray,Pending,,,,
1002,Reema,03-04-1971,07-12-2019,CT-San,Pending,,,,
1003,Ashoke,14-09-1980,13-07-2019,MRI,Pending,Dave,Approved,,
1003,Francis,02-02-1965,16-07-2019,Blood Test,Pending,John,Rejected,,

ArrayIndexOutOfBounds exception for huge number of objects in array [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
When size of data is 600, there is no exceltion.
When the size of the data is 800 I am getting following exception, after completing all the iterations and exiting the loop at following line:
'imageAdapter = new ImageAdapter(MainActivity.getAppContext(), posters);'
Issue is not related to splitArray[] which is inside the loop. Please note that it works for smaller size data.
Please help.
FATAL EXCEPTION: main
Process: com.udacityproject.svs.popularmovies, PID: 12517
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
at com.udacityproject.svs.popularmovies.MainActivity$1.deliverResult(MainActivity.java:130)
at com.udacityproject.svs.popularmovies.MainActivity$1.deliverResult(MainActivity.java:57)
at android.support.v4.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:255)
at android.support.v4.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:80)
at android.support.v4.content.ModernAsyncTask.finish(ModernAsyncTask.java:487)
at android.support.v4.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:504)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Constructor for Image Adapter :
public ImageAdapter(#NonNull Context context, #NonNull Poster[] objects){
super(context, 0, objects);
posters = objects;
}
Function:
public void deliverResult(String[] data) {
if (data != null) {
Poster[] posters = new Poster[data.length];
for (int i=0; i<data.length; i++) {
String imagePath = "http://image.tmdb.org/t/p/w185/" ;
int imageId;
String title;
String overview;
String rating;
String releaseDate;
String[] splitArray;
try {
splitArray = data[i].split("[*]");
} catch (PatternSyntaxException e) {
e.printStackTrace();
return;
}
imagePath+=splitArray[2];
imageId = Integer.valueOf(splitArray[0]);
title = splitArray[1];
rating = splitArray[3];
overview = splitArray[4];
releaseDate = splitArray[5];
posters[i] = new Poster( imageId, imagePath, title, overview, rating, releaseDate);
}
imageAdapter = new ImageAdapter(MainActivity.getAppContext(), posters);
mMoviePoster.setAdapter(imageAdapter);
}
}
One of the line included between the 600th and 800th line is incomplete.
Add this following line :
assert splitArray.length > 4 : "Following line lacks a column: " + data[i];
after :
splitArray = data[i].split("[*]");
It should tell you which line lacks the fifth column

IndexOutOfBoundsException error in android studio [duplicate]

This question already has answers here:
Android List View Array Index Out Of Bounds Exception - No clues?
(4 answers)
Closed 5 years ago.
I have build an application the code is right. Still I am getting an error of
java.lang.IndexOutOfBoundsException: Invalid index 7, size is 7
whenever I am running app. Can't figure out what is the problem
I have checked many solution nothing helped me.
my code is
public class Lecture extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lecture);
List<List<String>> arrayOfListsA= new ArrayList<List<String>>();
SharedPreferences sharedPreferences=getSharedPreferences("MyData",MODE_PRIVATE);
String username=sharedPreferences.getString("username","NA");
String password=sharedPreferences.getString("password","NA");
TextView av=(TextView)findViewById(R.id.tvavg);
double sub=0,subt=0,prd=0,sec=0,btch=0,day=0,date=0;
try {
arrayOfListsA = new HttpGetLecture().execute(username,password).get();
List<String> subject = new ArrayList<String>();
List<String> subjecttype = new ArrayList<String>();
List<String> period = new ArrayList<String>();
List<String> section = new ArrayList<String>();
List<String> batch = new ArrayList<String>();
List<String> day1 = new ArrayList<String>();
List<String> date1 = new ArrayList<String>();
GridView gridView=(GridView) findViewById(R.id.gridLect1);
subject = arrayOfListsA.get(1);
subjecttype = arrayOfListsA.get(2);
day1= arrayOfListsA.get(3);
period= arrayOfListsA.get(4);
date1= arrayOfListsA.get(5);
section= arrayOfListsA.get(6);
batch= arrayOfListsA.get(7);
/*for(int i=0;i<subject.size();i++) {
sub = sub + parseInt(subject.get(i));
} */
/* for(int j=0;j<subjecttype.size();j++){
subt=subt+ parseInt(subjecttype.get(j));
}
for(int k=0;k<period.size();k++){
prd=prd+ parseInt(period.get(k));
}
for(int l=0;l<section.size();l++){
sec=sec+ parseInt(section.get(l));
}
for(int m=0;m<batch.size();m++){
btch=btch+ parseInt(batch.get(m));
}
*/
//avg= (out / per) * 100;
//av.setText("Average Attendance :- "+ String.valueOf(avg)+" %");
gridView.setAdapter(new CustomAdapterLecture(this,subject,subjecttype,period,section,batch,day1,date1));
} catch (InterruptedException e) {
e.printStackTrace();
e.getMessage();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
The index starts at 0 not at 1, you should get wrong value anyway.
its a good idea toi write unitTest for things like that, in order to find your error early.
Java array indexes start with 0 up to size-1 (inclusive).
You should fix your indexes accordingly:
subject = arrayOfListsA.get(1);
should be
subject = arrayOfListsA.get(0);
etc.
replace this
GridView gridView=(GridView) findViewById(R.id.gridLect1);
subject = arrayOfListsA.get(1);
subjecttype = arrayOfListsA.get(2);
day1= arrayOfListsA.get(3);
period= arrayOfListsA.get(4);
date1= arrayOfListsA.get(5);
section= arrayOfListsA.get(6);
batch= arrayOfListsA.get(7);
With
GridView gridView=(GridView) findViewById(R.id.gridLect1);
subject = arrayOfListsA.get(0);
subjecttype = arrayOfListsA.get(1);
day1= arrayOfListsA.get(2);
period= arrayOfListsA.get(3);
date1= arrayOfListsA.get(4);
section= arrayOfListsA.get(5);
batch= arrayOfListsA.get(6);
As index start with 0 not 1

java.lang.IndexOutOfBoundsException: Invalid index 50, size is 50 [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 7 years ago.
I am getting a string which I'm trying to convert to JSONArray. The length of the JSONArray is getting OK (if its 100 or 5000). but I am getting "java.lang.IndexOutOfBoundsException: Invalid index 50, size is 50". Below is my code.
try
{
JSONArray jsonArray = new JSONArray(returndResultForSNID);
System.out.println("jsonArray: "+jsonArray.length());
for(int i = 0; i < jsonArray.length(); i++)
{
snid = jsonArray.getJSONObject(i).getString("snid");
//number = jsonArray.getJSONObject(i).getString("phone");
phoneContactsDTOArrayList.add(new PhoneContactsDTO( contactNameArr.get(i).toString() , contactPhoneNumberArr.get(i).toString(), snid, "") );
//System.out.println( "Could jsonArray parse malformed JSON: " + snid +" _> "+number);
}
}
catch (Exception e)
{
System.out.println( "JSONArray error: " + e.toString() );
}
Arrays are 0 based.
It means that an array of size 50 has index from 0 to 49.
contactNameArr and contactPhoneNumberArr are probably smaller than the size of jsonArray. In particular jsonArray has a size bigger than 51 and one of the others has a dimension of 50.

Null Pointer Exception from JCalander Combobox

My Java Application produces Null Pointer Exception from JCalander Combobox. I tried to catch the error. But that didnt work. Can someone assist me to fix this. Please.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.util.Calendar.setTime(Calendar.java:1106)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:955)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:948)
at java.text.DateFormat.format(DateFormat.java:336)
at org.freixas.jcalendar.JCalendarCombo.paramString(JCalendarCombo.java:780)
at java.awt.Component.toString(Component.java:8095)
tbmodel = (DefaultTableModel)tblItmQty.getModel();
System.out.println(calRecvDate.getDate());
try{
if(calRecvDate.getDate()==null){ // Error
JOptionPane.showMessageDialog(null, "Please Select Shippment Received Date");
calRecvDate.requestFocus();
}else if(txtShipSs.getText().isEmpty()){
////////////////////////////////////////////////////////////////
if (inputValidate() == true) {
try {
String shipId = txtShipId.getText();
String invID = txtInvoice.getText();
String shipSs = txtShipSs.getText();
String address = txtNtfAddress.getText();
String sipper = txtAShipper.getText();
String vessal = txtVessal.getText();
Date rcvDate = calRecvDate.getDate(); // Jcalander
String consignee = txtConsigne.getText();
ArrayList<ShippmentItems> shipItems = new ArrayList<ShippmentItems>();
tbmodel = (DefaultTableModel) tblItmQty.getModel();
for (int i = 0; i < tbmodel.getRowCount(); i++) {
String itmcode = (String) tbmodel.getValueAt(i, 0);
String itmName = (String) tbmodel.getValueAt(i, 1);
int qty = (int) tbmodel.getValueAt(i, 2);
ShippmentItems shpItems = new ShippmentItems(shipId, itmcode, itmName, qty);
shipItems.add(shpItems);
}
Since this throws the NPE:
calRecvDate.getDate()==null
The calRecvDate variable is null, and you will either need to check if it's null before using it, or make sure that it isn't null by tracing back in your code to where you think you've initialized it and fix the problem (since it isn't initialized).
To check if it's null, you could do:
if (calRecvDate != null) {
// use the calRecvDate variable here
} else {
// initialize the calRecvDate variable here
// or perhaps better, display a JOptionPane error message to the user
// that the date hasn't been selected, and exit this method by calling return:
return;
}
Again, don't use try/catch blocks to handle NullPointerExceptions.

Categories