Android Null Pointer Exception SQLite - android

I am trying to get book data from my database but I keep running into a NullPointerException. I have a double array Entries that I want filled with a book item and its 5 corresponding details. I know I have extra elements in the InventoryAdapter array that I dont use in this method, but I keep it there since I use it elsewhere.
The error occurs at Entries[i][0] = InventoryAdapter.getInventoryByISBN(records[i][0])[1]; and by extension at Cursor cursor = db.rawQuery(query, new String[] {ISBN});
Why would the error be at the Cursor? I would have thought the error would probably occur with calling an array location that doesn't exist.
Main code
int numEntries = 2;
Entries = new String[numEntries][5];
int totalCount = 0;
if (BuildConfig.DEBUG)
Log.d(debug.LOG, "numEntries="+numEntries);
Toast.makeText(ReportsByDateScreen.this, "numEntries="+numEntries, Toast.LENGTH_LONG).show();
// Set up search array
for(int i = 0; i < numEntries; i++)
{
Entries[i][0] = InventoryAdapter.getInventoryByISBN(records[i][0])[1];
Entries[i][1] = InventoryAdapter.getInventoryByISBN(records[i][0])[2];
Entries[i][2] = InventoryAdapter.getInventoryByISBN(records[i][0])[4];
Entries[i][3] = InventoryAdapter.getInventoryByISBN(records[i][0])[3];
for(int j = 0; j < records.length; j++)
{
if(records[j][0].equals(InventoryAdapter.getInventoryByISBN(records[i][0])[0]))
{
totalCount+=Integer.parseInt(InventoryAdapter.getInventoryByISBN(records[i][0])[8]);
}
}
Entries[i][4] = ((Integer)totalCount).toString();
reportArray.add(new ReportsItem(records[i][0],Entries[i]));
totalCount = 0;
}
InventoryAdapter
public static String[] getInventoryByISBN(String ISBN)
{
String[] entry = new String[9];
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
for(int i = 0; i < 9; i++)
entry[i] = "Not Found";
return entry;
}
cursor.moveToFirst();
//put data into respective variable
int publish = cursor.getInt(cursor.getColumnIndex("PUBLISH_DATE"));
String publishdate = ((Integer)publish).toString();
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
String callNumber = cursor.getString(cursor.getColumnIndex("CALL_NUMBER"));
int available = cursor.getInt(cursor.getColumnIndex("AVAILABLE_COUNT"));
String availablecount = ((Integer)available).toString();
int inventory = cursor.getInt(cursor.getColumnIndex("INVENTORY_COUNT"));
String inventorycount = ((Integer)inventory).toString();
int due = cursor.getInt(cursor.getColumnIndex("DUE_PERIOD"));
String dueperiod = ((Integer)due).toString();
int checkoutcount = cursor.getInt(cursor.getColumnIndex("COUNT"));
String count = ((Integer)checkoutcount).toString();
//combine variables into one array
entry[0] = ISBN;
entry[1] = title;
entry[2] = author;
entry[3] = publishdate;
entry[4] = callNumber;
entry[5] = availablecount;
entry[6] = inventorycount;
entry[7] = dueperiod;
entry[8] = count;
cursor.close();
return entry;
}

There is 2 different possibilities here :
ISBN is null (and by extension records[i][0] is null too);
db is null
I'll look into that if I were you.
Use the debugger.
I can tell you much because you don't post the code of your init of the SQLiteDatabase.

Related

SQLite in Android

I want to read bookname field in database, but it does not work in this class.
How can I use this class?
public Person readPerson(String bookkname) {
Person person = null;
String[] columns = new String[]{"id" ,"bookname"};
String selection = "bookname=?";
String[] selectionArgs = new String[]{ bookkname};
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
SQLiteDatabase database = null;
try {
database = sqLiteOpenHelper.getWritableDatabase();
Cursor cursor = database.query("tbl_persons", columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if(cursor != null && cursor.moveToFirst()) {
int idIndex = 0;
int payIndex = 1;
int lastunitIndex = 2;
int lastlessenIndex = 3;
int booknameIndex = 4;
int maxfreeunitIndex = 5;
long personId = cursor.getLong(idIndex);
String personpay = cursor.getString(payIndex);
String personlastunit = cursor.getString(lastunitIndex);
String personlastlessen = cursor.getString(lastlessenIndex);
String personbookname = cursor.getString(booknameIndex);
String personmaxfreeunit = cursor.getString(maxfreeunitIndex);
person = new Person();
person.setId(personId);
person.setpay(personpay);
person.setlastunit(personlastunit);
person.setlastlessen(personlastlessen);
person.setbookname(personbookname);
person.setmaxfreeunit(personmaxfreeunit);
}
} catch (Exception ex) {
Log.d("Database", "Exception:" + ex.getMessage());
} finally {
if (database != null && database.isOpen()) {
database.close();
}
}
return person;
}
I try call readperson class like inner but cant give data from data base or give to me packagename
Please tell to me way of calling this class ?
PersonDatabaseAdapter databaseAdapteer = new PersonDatabaseAdapter(Main2Activity.this);
Person persoon = new Person();
databaseAdapteer = new PersonDatabaseAdapter(this);
username = databaseAdapteer.readPerson(pass.toString());

The type of expression must be an array type but it resolved to string

am developing a application which fetches some data from Database..but it shows this error
private void add() {
db = (new DbHelper(this)).getReadableDatabase();
String query = "select * from stock where product = ?";
String list_data;
Cursor c = db.rawQuery(query, new String[] { list_data });
c.moveToFirst();
final CharSequence[] items = new CharSequence[list_data.length()];
for (int i = 0; i < list_data.length(); i++) {
items[i] = list_data[i];//here is the error
}
Try this
db = (new DbHelper(this)).getReadableDatabase();
String query = "select * from stock where product = ?";
String list_data;
Cursor c = db.rawQuery(query, new String[] { list_data });
c.moveToFirst();
final CharSequence[] items = new CharSequence[list_data.length()];
for (int i = 0; i < list_data.length(); i++) {
items[i] = list_data.charAt(i);
}
You can get char from String using charAt(int index) method
Your variable, list_data by virtue of being a String variable cannot be used like an array. When I say it cannot be used as an array, I'm specifically talking about the square brackets you used for referencing individual characters within the string.
items[i] = list_data[i];
As Aniruddh correctly pointed out, you must use the built in charAt() method which is defined under the String class.
items[i] = list_data.charAt(i);
Refer the definition for details-
https://developer.android.com/reference/java/lang/String.html#charAt%28int%29
Cheers.

Editing cursor data before display

I'm new in android and Java world and I want to edit cursor data result before displaying it. To do so I wrote the following code
private static final String[] INTERNAL_COLUMNS_1 = new String[] {
MediaStore.Audio.Media._ID,MediaStore.Audio.Media.TITLE};
private static final String[] INTERNAL_COLUMNS_2 = new String[] {
MediaStore.Audio.Media._ID, "fixString(" + MediaStore.Audio.Media.TITLE + ")"};
private Cursor getInternals() {
return query(
MediaStore.Audio.Media.INTERNAL_CONTENT_URI, INTERNAL_COLUMNS_1,
constructBooleanTrueWhereClause(mFilterColumns),
null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
}
private Cursor mCursor = new SortCursor(getInternals());
public String fixString(String oldstr)
{
String str = new String(oldstr);
str = str.replace("_", " ");
if (Character.isLowerCase(str.charAt(0)))
{
str = str.substring(0,1).toUpperCase() + str.substring(1,str.length());
}
for(int i=1;i<str.length();i++)
{
if ((Character.isUpperCase(str.charAt(i)))
&& (Character.isLetter(str.charAt(i)))
&& (Character.isLowerCase(str.charAt(i - 1)))
&& (Character.isLetter(str.charAt(i - 1))))
{
str = str.substring(0,i) + " " + str.substring(i,str.length());
}
}
return str;
}
public static void main(){
for (int i = 0; i < mCursor.getCount(); i++)
{
mCursor.moveToPosition(i);
String string = mCursor.getString(1);
Log.d("OUT"," string = "+ string);
}
Using INTERNAL_COLUMNS_1, the log shows
TomSkinner
Jack_Smith
foxRayan
I want to have as the cursor result :
Tom Skinner
Jack Smith
Fox Rayan
So I used INTERNAL_COLUMNS_2, but I have exception
android.database.sqlite.SQLiteException: no such function: fixString
Does any one know how to do so, or any other idea ?
You need to either change the data before it gets into the database, or change it before you display it. What you are trying to do is create a function and use it in a SQLite query, which will not work. Removing the fixString parts from the SQL query and then using it on the string from the cursor is one way it will work.
for (int i = 0; i < mCursor.getCount(); i++)
{
mCursor.moveToPosition(i);
String string = mCursor.getString(1);
Log.d("OUT"," string = "+ fixString(string));
}

how to get the database value to a String array in android(sqlite Database)

I have a database name "CUED" (sqlite Android)it have a table HELLO which contain a column NAME I can get the value to String from that column.
Let me show you my code section
myDB =hello.this.openOrCreateDatabase("CUED", MODE_PRIVATE, null);
Cursor crs = myDB.rawQuery("SELECT * FROM HELLO", null);
while(crs.moveToNext())
{
String uname = crs.getString(crs.getColumnIndex("NAME"));
System.out.println(uname);
}
It will print the value one by one. Now what I need is that I want to get the column values from database and so that I can store it in a String Array.
You already did the hard part... the array stuff is pretty simple:
String[] array = new String[crs.getCount()];
int i = 0;
while(crs.moveToNext()){
String uname = crs.getString(crs.getColumnIndex("NAME"));
array[i] = uname;
i++;
}
Whatever, I always recommend to use collections in cases like this:
List<String> array = new ArrayList<String>();
while(crs.moveToNext()){
String uname = crs.getString(crs.getColumnIndex("NAME"));
array.add(uname);
}
In order to compare the arrays, you can do things like this:
boolean same = true;
for(int i = 0; i < array.length; i++){
if(!array[i].equals(ha[i])){
same = false;
break;
}
}
// same will be false if the arrays do not have the same elements
String[] str= new String[crs.getCount()];
crs.movetoFirst();
for(int i=0;i<str.length();i++)
{
str[i] = crs.getString(crs.getColumnIndex("NAME"));
System.out.println(uname);
crs.movetoNext();
}
Enjoy it
This is my code that returns arraylist contains afield value:
public ArrayList<String> getAllPlayers() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery("SELECT " + serailnumber + " as _id, " + title
+ " from " + table, new String[] {});
ArrayList<String> array = new ArrayList<String>();
while (cur.moveToNext()) {
String uname = cur.getString(cur.getColumnIndex(title));
array.add(uname);
}
return array;
}

Cursor doesn't find columns?

I tried to load a list of values from a table, but the cursor doesn't find the columns?
The Code which is buggy:
public final AccessToken[] fetchAccessTokenByServerId(final long serverId) {
final Cursor c = db.query(
ACCESS_TOKEN_TABLE,
new String[] { ACCESS_TOKEN_COL_ID, ACCESS_TOKEN_COL_VALUE },
ACCESS_TOKEN_COL_SERVER_ID + "=?",
new String[] { Long.toString(serverId) },
null,
null,
null);
AccessToken[] result = new AccessToken[c.getCount()];
for (int i = 0; i < result.length; i++) {
long id = c.getLong(c.getColumnIndexOrThrow(ACCESS_TOKEN_COL_ID));
String value = c.getString(c.getColumnIndexOrThrow(ACCESS_TOKEN_COL_VALUE));
result[i] = new AccessToken(value, id, serverId);
c.moveToNext();
}
return result;
}
public static final String COL_ID = "_id";
public static final String ACCESS_TOKEN_TABLE = "accesstoken";
public static final String ACCESS_TOKEN_COL_ID = COL_ID;
public static final String ACCESS_TOKEN_COL_SERVER_ID = "server_id";
public static final String ACCESS_TOKEN_COL_VALUE = "value";
But the first two statements in the for-loop fails:
Index -1 is requested, with a size of
1
The table exists with the columns: _id (= int), server_id (= int) and value (= string)
There is one entry: 1, 1, test
The parameter of the function is 1.
Sincerely
xZise
Just after initializing your cursor, do this:
c.moveToFirst();
In this part of the code I recommend it this way
Original:
AccessToken[] result = new AccessToken[c.getCount()];
for (int i = 0; i < result.length; i++) {
long id = c.getLong(c.getColumnIndexOrThrow(ACCESS_TOKEN_COL_ID));
String value = c.getString(c.getColumnIndexOrThrow(ACCESS_TOKEN_COL_VALUE));
result[i] = new AccessToken(value, id, serverId);
c.moveToNext();
}
Modified:
if (c.moveToFirst()){
int rowCount = c.getCount();
AccessToken[] result = new AccessToken(rowCount);
int recCount = 0;
while (!c.isAfterLast()){
long id = c.getLong(c.getColumnIndexOrThrow(ACCESS_TOKEN_COL_ID));
String value = c.getString(c.getColumnIndexOrThrow(ACCESS_TOKEN_COL_VALUE));
result[recCount++] = new AccessToken(value, id, serverId);
c.moveToNext();
}
c.close(); // <-- IMPORTANT!!!!
}

Categories

Resources