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
Related
This question already has answers here:
Two different ArrayList merge? [closed]
(2 answers)
Closed 4 years ago.
List<ExpenseDetailsWrapper> expenseDataList = reimbursementLocalService
.getAllExpenseByReimbursementId(reimbursementId);
long fileEntryId = 0;
String previewURL = StringPool.BLANK;
List<String> billUrlData = new ArrayList<String>();
List<String> finalMerge = new ArrayList<String>();
try {
for (int i = 0; i < expenseDataList.size(); i++) {
fileEntryId = expenseDataList.get(i).getFileEntryId();
if (fileEntryId > 0) {
FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(fileEntryId);
previewURL = DLUtil.getPreviewURL(fileEntry, fileEntry.getFileVersion(), themeDisplay, StringPool.BLANK);
}
renderRequest.setAttribute("previewUrl", previewURL);
finalMerge.add(billUrlData);
finalMerge.add(expenseDataList);//**Error is here**The method addAll(Collection<? extends String>) in the type List<String> is not applicable for the arguments (List<ExpenseDetailsWrapper>)
LOG.info("File Entries"+fileEntryId);
}
LOG.info(billUrlData);
renderRequest.setAttribute("previewUrl", billUrlData);
renderRequest.setAttribute("expenseDataList", expenseDataList);
} catch (Exception e) {
e.printStackTrace();
}
I have one list with POJO and another one with String.. but when i am trying to add two these list into one it gives me error
Can i append two list of different type??
Yes you can with List<Object> expenseDataList but while retrieving you need to be careful and cast it.
for(Object obj : expenseDataList)
{
if(obj instanceof YourPOJO)
//take action
}
I'm trying to take data from a backend(I'm using parse.com), put it into an array and use it to populate a ListView via an adapter. I parse multiple objects into a list and then put "names" and "ids" into two separate string arrays.
Now, my problem is that data disappears as soon as I add the next position to the array. I've spent quite a while figuring this out with debug logs, and it appears as if names[0] is displayed in the log properly when requested right after I write it. If I try to access names[0] after writing names[1] I get a null pointer exception - println needs a message, and the app crashes. When not trying to access the data via debug log, the listview is populated by a proper number of entries, yet the data that should've come from names[] and ids[] is empty. Here's the code where everything goes horribly wrong:
names = new String[2];
ids = new String[2];
ParseQuery<ParseObject> query = ParseQuery.getQuery("TestItem");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
int size = objects.size();
int i = 0;
ParseObject obj;
while (i < size) {
obj = objects.get(i);
names[i] = obj.getString("name");
ids[i] = obj.getString("objectId");
i++;
}
/*The following code is fairly irrelevant(I think?) since the error appears
to be somewhere in the previous lines.*/
Bundle bundel = new Bundle();
bundel.putStringArray("names", names);
bundel.putStringArray("ids", ids);
ft = getSupportFragmentManager().beginTransaction();
screen = new Feed().newInstance(bundel);
ft.add(R.id.holder_frame, screen);
ft.commit();
} else {
}
}
});
I feel like it's something basic about managing arrays, but I can't seem to understand it. Please help :(
The following line seems to be fishy:
new Feed().newInstance(bundel);
newInstance method should be static method.
Make sure that you are adding the appropriate instance of fragment with the bundle information. If you don't figure it out, provide code in the Fragment.
Consider code below:
ParseQuery<ParseObject> query = ParseQuery.getQuery("TestItem");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
int size = objects.size();
String[] names = new String[size];
String[] ids = new String[size];
for (int i = 0; i < size; i++) {
ParseObject elem = objects.get(i);
names[i] = elem.getString("name");
ids[i] = elem.getObjectId();
}
/*The following code is fairly irrelevant(I think?) since the error appears
to be somewhere in the previous lines.*/
Bundle params = new Bundle();
params.putStringArray("names", names);
params.putStringArray("ids", ids);
ft = getSupportFragmentManager().beginTransaction();
screen = new Feed();
screen.setArguments(params);
ft.add(R.id.holder_frame, screen);
ft.commit();
} else {
Toast.make(<Current>Activity.this, "Error", ...).show();
}
}
});
I think this might be the problem:
int size = objects.size();
int i = 0;
ParseObject obj;
while (i < size) {
obj = objects.get(i);
names[i] = obj.getString("name");
ids[i] = obj.getString("objectId");
i++;
}
names and ids are initialised as
names = new String[2];
ids = new String[2];
You are looping over all of the elements in objects so if it has any more than two elements you will be writing outside the bounds of the names and ids arrays.
I am trying to create a method that will update a list that has already been created. Im not sure why this is not working?
It throws a null pointer exception.
This is my code:
private void UpdateJList(){
String query = "SELECT * FROM names WHERE TYA=?";
String partialSearch = "Sales";
try{
connect.pst = connect.con.prepareStatement(query);
connect.pst.setString(1, partialSearch);
connect.pst.execute();
ArrayList<String> add = new ArrayList<String>();
String[] items = {};
while (connect.rs.next()){
String result = connect.rs.getString("ACNO");
add.add(result);
int length = add.size();
DefaultListModel<String> model;
model = new DefaultListModel<String>();
for (int i=0; i<length; i++){
model.add(i, result);
}
jList1.setModel(model);
jList1.setSelectedIndex(0);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Thank you in advance!!
There are 2 major problems with that code:
In the while loop, you are creating many instances of DefaultListModel. That means, for each entry of the query result, you are restarting the list.
A nullpointer exception is produced by the line: connect.rs.next() because you didn't assign connect.rs with the query's resultset.
I am using Blackberry Plug-in and i am using Rich Lists of blackberry.
I want to make lists appear the same number of times as there are entries in the database table.
I m using the below code but it shows only one name in list view.
I need to show all the entries in database into list view...Kindly help me..
I have already used list.add(); inside the for loop but it is showing Exception: java.lang.IllegalStateException: Field added to a manager while it is already parented.
public static void richlistshow(){
String name = null;
list = new RichList(mainManager, true, 2, 0);
Bitmap logoBitmap = Bitmap.getBitmapResource("delete.png");
delete = new BitmapField(logoBitmap, Field.FIELD_HCENTER);
for (int c = 0; c < target_list.size();c++){
City tar_city = new City();
tar_city = (City)target_list.elementAt(c);
name = tar_city.get_city_name().toString();
}
//adding lists to the screen
list.add(new Object[] {delete,name,"time-date"});
}
You didn't posted full codes you are working with. But following code may help you to get rid of IllegalStateException. You were adding same BitmapField instance for every list entries, which caused the exception.
public static void richlistshow() {
final Bitmap logoBitmap = Bitmap.getBitmapResource("delete.png");
list = new RichList(mainManager, true, 2, 0);
for (int c = 0; c < target_list.size(); c++) {
// create a new BitmapField for every entry.
// An UI Field can't have more than one parent.
final BitmapField delete = new BitmapField(logoBitmap, Field.FIELD_HCENTER);
City tar_city = (City) target_list.elementAt(c);
final String name = tar_city.get_city_name().toString();
// add to list
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
list.add(new Object[] { delete, name, "time-date" });
}
});
}
}
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.