Getting "Variable might not initialized error" - android

I am creating function for Sqlite database and getting "variable might not initialized" error. I am trying to store sqlite data in string array.
public String[] gettitle()
{
String title[];
String s = "select Title from User_DB;";
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(s,null);
int a = 0;
while(cursor.moveToNext())
{
title[a] = cursor.getString(0);
a++;
}
return title;
}
it says title[] is not initialized but I dont understand why. I clearly initialized it.

You declare title. Allowed C language style is String title[]. In java one keeps the type expression together: String[] title;
String[] title;
This variable is uninitialized, reserves a memory slot for an array object, but the memory is not filled, initialized; it contains garbage. At its first usage of title the compiler issues an error.
In contrast class fields are initialized automatically by a default: here null, but for other types 0, false, 0.0 and so on.
Initialize the variable: give it an initial value.
For arrays that means set an array object. Arrays are fixed length, cannot grow, and thus:
String[] title;
title = new String[10];
Or shorter:
String[] title = new String[10];
Like fields also array elements are initialized with defaults, null.
Note you initialized a: int a = 0;.
Now you can use the array object through the variable:
title[a] = cursor.getString(0);
This was the point where the compiler saw the usage of a variable that still did not have a value.
So the code becomes:
public String[] loadTitles() {
String[] titles = new String[100];
String sql = "select Title from User_DB";
SQLiteDatabase db = getReadableDatabase();
int a = 0;
try (Cursor cursor = db.rawQuery(sql, null)) {
while (a < titles.length && cursor.moveToNext()) {
titles[a] = cursor.getString(0);
a++;
}
} // Calls cursor.close();
return Arrays.copyOf(titles, a);
}
Array.copyOf(array, newLength) make copy of the original array with as new length the number of read titles.
I have added the (weird) try-with-resources syntax which ensures that cursor is closed, even on exception or return happening inside the block.

Related

Receive an ArrayIndexOutOfBoundsException when trying to access String array

I have a model, lineModel that I am using to populate an array items for my gridAdapter. My model works fine when I populate the entries manually. For example:
lineModel[] items = {
new lineModel(2, "B", "", "#52D017", 5, 10, 30),
new lineModel(3, "C", "", "#000000", 4, 8, 30),
};
However, when populating items with SQLite I receive the ArrayIndexOutOfBoundsException
Specifically:
04-15 15:50:21.322: E/AndroidRuntime(26804): java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
04-15 15:50:21.322: E/AndroidRuntime(26804): at com.idealiner.metrosleepuniversal.model.GridModel.getLines(GridModel.java:68)
Line 68 is when I call lineModel and populate it with the values from cursor.
items[i] = new lineModel(i, c.getString(c_line), c.getString(c_name), c.getString(c_ccolor), 0, 0, 0);
The method getLines() is supposed to return the object array, but somewhere in the while() loop I believe there is a problem, most likely when populating the array.
Any help/advice/guidance would be appreciated.
The entire method, getLines, is below:
public lineModel[] getLines() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"*"};
String sqlTables = "lines";
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, null, null,
null, null, null);
lineModel[] items = {};
int i=0;
int c_line = c.getColumnIndex("line_id");
int c_name = c.getColumnIndex("line_name");
int c_ccolor = c.getColumnIndex("line_color");
int c_tcolor = c.getColumnIndex("text_color");
c.moveToFirst();
if (c != null) {
while(c.moveToNext()) {
items[i] = new lineModel(i, c.getString(c_line), c.getString(c_name), c.getString(c_ccolor), 0, 0, 0);
i++;
}
c.close();
}
return items;
}
Well, you're creating a zero-length array:
lineModel[] items = {};
so there's no items[i] when you try assigning to it.
If you can use c.getCount(), as Flavio Faria suggests, set the initial length to that. Otherwise, I suggest you use an ArrayList, and .add() items to it as you go along. You can obtain the resulting array with .toArray()
In fact, you might consider using an ArrayList anyway and passing it up as the return value, ,that's very often a good idea.
Another alternative - which depends on how you use those line model items - is to pass an Iterator instead of an array (as what you're doing is essentially iterating into an array.
You can't use "*" together with column names. You must either use only "*" or you must declare each column in the array. So, don't do it like this:
String[] sqlSelect = {"0 _id", "*"};
Add each one of them instead:
String[] sqlSelect = { "line_id", "line_name", "line_color", "text_color"};
Or:
String[] sqlSelect = { "*" };
You must also remove c.moveToFirst() call in order to avoid skipping the first row of the cursor, since c.moveToNext() already does this job for you.
Your array must also be large enough to hold all your items:
lineModel[] items = new lineModel[c.getCount()];
Besides that, keep in mind that class names in Java start with a capital letter.

How to store data from SQLite in a 2D Arraylist?

I need to get all of the information from my SQLite Database and store it in an Array List, or some other way if there is a better way. My database has 6 columns, here is how I am attempting to extract the data and store it in an Arraylist index;
db.open();
for(int i = 0; i<= amount; i++)
{
Cursor c = db.fetchAllNotes();
if (c.moveToFirst())
{
do {
mid = c.getString(0);
place =c.getString(1);
info =c.getString(2);
coordl1 =c.getString(3);
coordl2 =c.getString(4);
colour =c.getString(5);
//code here to store each string in an Array index
mapSetupList.add(mid,place,info,coordl1,coordl2,colour);
}while (c.moveToNext());
}
}
db.close();
I know how to create an Array list, but I do not know how to store 6 strings in one index, I experimented with 2D Arraylists, but this seemed to be too complicated and I didn't think it was the right way to do it. Is there a better way to do this, if not how can this be done with Arraylists?
What about to create one own defined Object that will wrap all columns as properties?
public class Foo {
private int id; // alternative to id column in db
private String type;
private String date;
...
public void setId(int id) { // setter
this.id = id;
}
public int getId() { // getter
return this.id;
}
}
Then create ArrayList<Foo> and now you can simply save data from SQLite into ArrayList:
public void store() {
Cursor c = null; // first declare and initialise appropriate objects
ArrayList<Foo> foos = new ArrayList<Foo>();
Foo member = null;
try {
c = db.rawQuery(query, whereArgs); // perform query
if (c.moveToFirst()) { // move cursor to first row because implicitly
do { // cursor is position before first row
member = new Foo(); // for each row create new Foo
member.setId(c.getInt(0)); // initialise properties
member.setType(c.getString(1));
member.setDate(c.getString(2));
...
foos.add(member); // add Foo into ArrayList
} while (c.moveToNext()); // it moves cursor to next row
}
}
finally { // in finally block release datasource(s), cursor(s)
if (c != null) {
c.close();
}
if (db != null && db.isOpen()) {
db.close();
}
}
}
Note: I recommend this approach. It's clear, safe and effective. Don't forget to release any datasources, cursors after work is done to avoid usually thrown exceptions like cursor is already open, database is already closed etc.
Update:
I am unsure about the class example, with the defined object and
getters and setters, can you please elaborate before I try this? Thank
you!!
So getters and setters are methods which are used "generaly "for manipulating with properies of Object to preserve Encapsulation - very important thing in OOP. Setters are used for initialising properties and getters for getting properties of Object.
Now i wrote for you example of method for store data from sqlite into ArrayList. There is this line:
member.setId(c.getInt(0));
where setId(c.getInt(0)) is setter of Foo Object with one Integer as parameter and with this method now you will fill up id value with data from Cursor.
Create a Class that contains all the informations that you like, and then create an instance of it then add that instance to the ArrayList.

Cursror into string error cursor.getcolumnIndex Key_titles and therefore cant fill my arraylist

Cursor curz=mDbHelper.fetchAllRemindersG();
startManagingCursor(curz);
ArrayList<String> mArrayList = new ArrayList<String>();
String name =curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
for(curz.moveToFirst(); curz.moveToNext(); curz.isAfterLast())
{ mArrayList.add(name); }
name_Val = (String[]) mArrayList.toArray(new String[mArrayList.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,name_Val);
txtPhoneName.setAdapter(adapter);
I am filling a autocompletetextview and i get an error at String name =curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
it just can't get the correct column index it forcecloses ive tried to wirte mdbHelper.KEY_TITLE or just KEY_TITLE but it was the same error
curz.moveToFirst()
String name =curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
do {
mArrayList.add(name);
}while(curz.moveToNext());
First you need to move to first row, then you can get something from it. Because when cursor is created, the pointer points to the -1 index or you can say it points to beforeFirst.
Cursor curz=mDbHelper.fetchAllRemindersG();
startManagingCursor(curz);
// setTheme(android.R.style.Theme_Light);
curz.moveToFirst();
ArrayList<String> mArrayList = new ArrayList<String>();
if (curz.getCount() > 0)
{
do
{
String name = curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
if(name!=null)
{
mArrayList.add(name);
}
}while (curz.moveToNext());
}

Convert Android Cursor to ArrayList of arrays

I try to convert my Cursor data to a arraylist. But at the end all the data in the arraylist is overwrited with the last row. What do i do wrong?
Cursor c = myDbHelper.getLvl1Cata();
String[] data = new String[3];
c.moveToFirst();
while(!c.isAfterLast()) {
data[0] = Integer.toString(c.getInt(0));
data[1] = c.getString(1);
data[2] = Integer.toString(c.getInt(2));
Log.e("cc", data[1]);
catalogueData.add(data);
c.moveToNext();
}
Try this
Cursor c = myDbHelper.getLvl1Cata();
String[] data;
if (c != null) {
while(c.moveToNext()) {
data = new String[3]; // Note this addition
data[0] = Integer.toString(c.getInt(0));
data[1] = c.getString(1);
data[2] = Integer.toString(c.getInt(2));
Log.e("cc", data[1]);
catalogueData.add(data);
}
c.close();
}
data is an array of strings. In the original code, you added the same array to your catalogueData structure several times. You changed the value of the array's contents each time, but it was still the same array object. So you ended up with catalogueData holding several references to a single array, and that array can only have one value for data[0]: the last thing you set it to.
This answer fixes that by using a new and different array for each row in the cursor.
Try this:
if(mycursor!=null){
do{
TextView name = (TextView)view.findViewById(R.id.contact_name);
name.setText(cursor.getString(cursor.getColumnIndex
(Displayname)));
mycursor.moveToNext();
}while (mycursor.isLast());
}
Put String[] data = new String[3]; into the while loop. You're overwriting the array object with each iteration.

Android: Create array of ROW_IDS from cursor - but how?

I have a db collection (SQLite) and i want to create an array of the ROW_IDS. I think the following should work:
db.open();
String Chapter = "Something";
Cursor c = db.getSetsByChapter(Chapter);
int[] ids = {};
if (c.moveToFirst()){
int i = 0;
do {
ids[i] = Integer.parseInt(c.getString(0));
i++;
} while (c.moveToNext());
}
db.close();
Toast.makeText(this,"The array contains " + ids.length + " elements",Toast.LENGTH_LONG).show();
but i keep getting:
Unable to start activity Component ... java.lang.ArrayIndexOutOfBoundsException
I'm very new to java and android coding. I have been at this for 3 days and loosing it!
First, you need to show us what line the exception is occuring.
Second, int[] ids = {}; declares an array of ints with length 0. You then try to
ids[i] = Integer.parseInt(c.getString(0));
put data into index 0. This isn't possible, and thus an array index out of bounds exception.
You need to allocate the array. Use a List<int> and then convert the list to an integer array

Categories

Resources