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
Related
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
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
So, I was trying to add a class to an ArrayList, but when I do it gives me a Null Pointer Exception. I'm sure I am just overlooking a variable that I thought was initialized, but I can't figure it out.
This is the class:
enum WebType { GoogleResult, Webpage };
public class Webpage {
WebType type;
String pageName;
String content;
String url;
String MLA = "";
public Webpage(String pageName, String content, String url, WebType type){
this.type = type;
this.pageName = pageName;
this.content = content;
this.url = url;
this.MLA = ""; // Temp
}
// TODO: Make Citation Maker
}
This is where I add the class to the ArrayList:
public void Start(){
for(Integer i = 0; i < tags.size(); i++){
if(tags.get(i) == null)
return;
Webpage page = Google(tags.get(i));
parseList.add(page); // The Error is on this line!
log.append("Added " + page.url + " to parse list");
}
for(Integer i = 0; i < parseList.size(); i++){
ParsePageCode(parseList.get(i));
}
}
Here is the Google function, it googles whatever you tell it to and returns the page information:
public Webpage Google(String search){
String url = "https://www.google.com/search?q=" + search;
String content = "";
try {
URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.append("\n Unsupported Encoding Contacting Google");
}
try {
content = GetPageCode(url);
} catch (IOException e) {
log.append("\n Unable To Reach Google");
log.append(e.getMessage());
}
Webpage w = new Webpage("Google Result For " + search, content, url, WebType.GoogleResult);
// System.out.println(search + url + WebType.GoogleResult);
return w;
}
Any Ideas?
On the line that is throwing the exception, parseList is the only variable being dereferenced. The only other variable on that line is page, and it doesn't matter if page is null because you can add null elements to a List. So, it must be parseList causing the NPE.
Actually there is no problem adding null to a collection of Objects. Retrieving the object and invoking its members later may cause NPE.
You have told is that the problem is on the line where you do add the object. The only way there to cause NPE is calling add() upon null. So that's your collection parseList that is not initialized yet. Maybe it's a field in the class and was never initialized to an actual object of type ArrayList, but it's only declared.
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.
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.
I have many questions about this project that I'm working on. It's a virtual database for films. I have a small MovieEntry class (to process individual entries) and a large MovieDatabase class that keeps track of all 10k+ entries. In my second searchYear method as well as subsequent methods I get the error "variable g (or d or whatever) might not have been initialized."
I also get a pop-up error that says Warnings from last compilation: unreachable catch clause. thrown type java.io.FileNotFoundException has already been caught. I'm positively stumped on both. Here's the code:
public class MovieDatabase
{
private ArrayList<MovieEntry> Database = new ArrayList<MovieEntry>();
public MovieDatabase(){
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
}
public int countTitles() throws IOException{
Scanner fileScan;
fileScan = new Scanner (new File("movies.txt"));
int count = 0;
String movieCount;
while(fileScan.hasNext()){
movieCount = fileScan.nextLine();
count++;
}
return count;
}
public void addMovie(MovieEntry m){
Database.add(m);
}
public ArrayList<MovieEntry> searchTitle(String substring){
for (MovieEntry title : Database)
System.out.println(title);
return null;
}
public ArrayList<MovieEntry> searchGenre(String substring){
for (MovieEntry genre : Database)
System.out.println(genre);
return null;
}
public ArrayList<MovieEntry> searchDirector (String str){
for (MovieEntry director : Database)
System.out.println(director);
return null;
}
public ArrayList<String> searchYear (int yr){
ArrayList <String> yearMatches = new ArrayList<String>();
for (MovieEntry m : Database)
m.getYear(yr);
if(yearMatches.contains(yr) == false){
String sYr = Integer.toString(yr);
yearMatches.add(sYr);
}
return yearMatches;
}
public ArrayList<MovieEntry> searchYear(int from, int to){
ArrayList <String> Matches = new ArrayList<String>();
for(MovieEntry m : Database);
m.getYear();
Matches.add();
return Matches;
}
public void readMovieData(String movies){
String info;
try{
Scanner fileReader = new Scanner(new File("movies"));
Scanner lineReader;
while(fileReader.hasNext()){
info = fileReader.nextLine();
lineReader = new Scanner(info);
lineReader.useDelimiter(":");
String title = lineReader.next();
String director = lineReader.next();
String genre = lineReader.next();
int year = lineReader.nextInt();
}
}catch(FileNotFoundException error){
System.out.println("File not found.");
}catch(IOException error){
System.out.println("Oops! Something went wrong.");
}
}
public int countGenres(){
ArrayList <String> gList = new ArrayList<String>();
for(MovieEntry m : Database){
String g = m.getGenre(g);
if(gList.contains(g) == false){
gList.add(g);
}
return gList.size();
}
}
public int countDirectors(){
ArrayList <String> dList = new ArrayList<String>();
for(MovieEntry m : Database){
String d = m.getDirector(d);
if(dList.contains(d) == false){
dList.add(d);
}
return dList.size();
}
}
public String listGenres(){
ArrayList <String> genreList = new ArrayList<String>();
}
}
catch(IOException error){
System.out.println("Oops! Something went wrong.");
}
Its telling you that the FileNotFoundException will deal with what the IOException is catching, so the IOException becomes unreachable as in it will never catch an IO exceltion, why just not catch an Exception instead
As for the initialization
public int countDirectors(){
ArrayList <String> dList = new ArrayList<String>();
for(MovieEntry m : Database){
String d = m.getDirector(d); //THIS LINE
if(dList.contains(d) == false){
dList.add(d);
}
return dList.size();
}
The line String d = m.getDirector(d); might be the problem, d wont be initialised unless there is something in the MovieEntry and as far as i can see there will never be anything because you are initialising it to an empty array list
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
Maybe you should be passing a array of movies to the constructor and then add these movies to the Database variable ?
Seems like there are a number of issues with this code.
What parameter does MovieEntry.getGenre() expect? You may not use g in that case because it has not been defined yet.
The exception issue you mentioned means that the exception was already caught, or possibly never thrown. I believe that in this case the IOException is never thrown out from the code within the try block.
There are a number of methods that are supposed to return a value but do not, example:
public String listGenres(){
ArrayList <String> genreList = new ArrayList<String>();
}
Also, it is a java naming convention to use lower case first characters (camel case) for values:
private ArrayList<MovieEntry> database = new ArrayList<MovieEntry>();
Oh, and do you need to re-initialize the database variable in the constructor?:
public MovieDatabase(){
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
}
Hope this is helpful.