Android - Populating sqlite table takes long - android

I had this problem a couple of months before and now it is time to get back to it.
I query the phone's calllog into a database, but it takes around 30 seconds to populate the table. It looks like querying takes around 1 sec, but the population takes forever, although the phone stores only the last 500 calls. Why is it so slow? Am I doing something wrong?
I test it only on my phone, since I have only 8 items in the emulator's calllog.
final String[] projection = null;
HotOrNot infoA = new HotOrNot(Charts.this);
infoA.open();
infoA.createtable_Calls();
infoA.deleteAllEntries_Calls();
infoA.close();
final Context context = getApplicationContext();
final String selection = null;
final String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
Cursor c = context.getContentResolver().query(android.provider.CallLog.Calls.CONTENT_URI, projection, selection, null, sortOrder);
while (c.moveToNext()) {
String callLogID = c.getString(c.getColumnIndex(android.provider.CallLog.Calls._ID));
int numberColumn = c.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int dateColumn = c.getColumnIndex(android.provider.CallLog.Calls.DATE);
int typeColumn = c.getColumnIndex(android.provider.CallLog.Calls.TYPE);
int durationColumn = c.getColumnIndex(android.provider.CallLog.Calls.DURATION);
int person = c.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
String number = c.getString(numberColumn);
int duration = c.getInt(durationColumn);
String personname = c.getString(person);
long callDate = c.getLong(dateColumn);
int callType = c.getInt(typeColumn);
if (duration >= 0)
{
switch (callType) {
case 1:
duration_in = duration;
duration_out = 0;
break;
case 2:
duration_out = duration;
duration_in = 0;
break;
case 3:
duration_in = 0;
duration_out = 0;
break;
}
}
//Here comes the slow part
HotOrNot info = new HotOrNot(Charts.this);
info.open();
info.pop
ulate_Calls(personname, number, String.valueOf(callType), Integer.toString(duration), Long.toString(callDate), callLogID);
info.close();
}
This is the populating function:
public long populate_Calls(String name, String phone, String type, String duration, String date, String contactid) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_PHONE, phone);
cv.put(KEY_TYPE, type);
cv.put(KEY_DURATION, duration);
cv.put(KEY_DATE, date);
cv.put(KEY_CONTACTID, contactid);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
EDIT:
To Andreas Ka's and twaddington's answers I modified the population method in the SQLiteOpenHelper class, but unfortunately it did not make a difference:
public long populate_Calls(String name, String phone, String type, String duration, String date, String contactid) {
ContentValues cv = new ContentValues();
try {
ourDatabase.beginTransaction();
cv.put(KEY_NAME, name);
cv.put(KEY_PHONE, phone);
cv.put(KEY_TYPE, type);
cv.put(KEY_DURATION, duration);
cv.put(KEY_DATE, date);
cv.put(KEY_CONTACTID, contactid);
ourDatabase.yieldIfContendedSafely();
ourDatabase.setTransactionSuccessful();
} finally {
ourDatabase.endTransaction();
}
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
EDIT2:
Posting the whole code based on Babibu and twaddington's answers. By the way the temp_ arrays are now LinkedLists, but that does not make a difference in time.
final String[] projection = null;
final Context context = getApplicationContext();
final String selection = null;
final String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
lv1 = (ListView) findViewById(R.id.ListView02);
HotOrNot infoA = new HotOrNot(Calllogs.this);
infoA.open();
infoA.createtable_Calls();
infoA.deleteAllEntries_Calls();
infoA.close();
pd = ProgressDialog.show(Calllogs.this, "Please wait..", "Loading data, it may take a few" +
" seconds based on the number of data.", false, true);
Cursor c = context.getContentResolver().query(android.provider.CallLog.Calls.CONTENT_URI, projection, selection, null, sortOrder);
while (c.moveToNext()) {
String callLogID = c.getString(c.getColumnIndex(android.provider.CallLog.Calls._ID));
int numberColumn = c.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int dateColumn = c.getColumnIndex(android.provider.CallLog.Calls.DATE);
int typeColumn = c.getColumnIndex(android.provider.CallLog.Calls.TYPE);
int durationColumn = c.getColumnIndex(android.provider.CallLog.Calls.DURATION);
int person = c.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
String number = c.getString(numberColumn);
int duration = c.getInt(durationColumn);
String personname = c.getString(person);
long callDate = c.getLong(dateColumn);
int callType = c.getInt(typeColumn);
if (duration >= 0)
{
switch (callType) {
case 1:
duration_in = duration;
duration_out = 0;
break;
case 2:
duration_out = duration;
duration_in = 0;
break;
case 3:
duration_in = 0;
duration_out = 0;
break;
}
}
temp_name.add(personname);
temp_num.add(number);
temp_type.add(String.valueOf(callType));
temp_dur.add(Integer.toString(duration));
temp_date.add(String.valueOf(callDate));
temp_id.add(callLogID);
} //end of while loop
HotOrNot infotemp = new HotOrNot(Calllogs.this);
infotemp.open();
for (int i=0; i<temp_name.size(); i++)
{
infotemp.populate_Calls(temp_name.get(i), temp_num.get(i), temp_type.get(i), temp_dur.get(i), temp_date.get(i), temp_type.get(i));
}
infotemp.close();
SOLUTION
I am posting twaddington's solution, which reduced the time from 8 seconds to less than 2:
HotOrNot infotemp = new HotOrNot(Calllogs.this);
infotemp.open();
// Get our database. You can do this however you wish, but
// it seems like since the database is contained in your `HotOrNot`
// object, it would be best to simply add a getter method to
// the class.
SQLiteDatabase db = infotemp.getDatabase();
try {
// Begin our transaction
db.beginTransaction();
// Loop over the array of calls and
// perform a db insert for each.
for (int i=0; i<temp_name.size(); i++) {
// Yield the database lock if requested. This will
// temporarily suspend our loop, but it should
// continue when the lock is opened.
db.yieldIfContendedSafely();
infotemp.populate_Calls(temp_name.get(i), temp_num.get(i),
temp_type.get(i), temp_dur.get(i), temp_date.get(i), temp_type.get(i));
}
// Mark our transaction as successful!
db.setTransactionSuccessful();
} finally {
// Always end the transaction!
db.endTransaction();
}
infotemp.close();

For each change that you make to the SQLite database a series of complicated
steps occur, including the creation of a journal file to rollback the
change if an error occurs. You can wrap your series of updates in a database
transaction to force SQLite to treat the entire series as a single operation.
This will be much more efficient.
try {
db.beginTransaction();
while (c.moveToNext()) {
// Yield the database lock if requested
db.yieldIfContendedSafely();
// Add your code here!
// ...
// Perform the database insert
populate_Calls(...);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}

Try to use a single transaction for the whole method:
http://notes.theorbis.net/2010/02/batch-insert-to-sqlite-on-android.html

You are inserting while browsing, this makes locks on your database. You need first finish your while loop and and only then insert it in your database. Just keep the data in same temporary linked List(better then array in your case, coz it got fast inserts)

Related

Data was not inserting in SqLite DataBase but Row count is increasing

When I try to insert my data in my sqlite table, The inserted data is not inserting but the primary key is increasing and row count also increasing. Dont know what the exact problem is. Please some one help what the issue is. I will add my code here. Pls some one help me
here I am adding to database
mylistDataBaseModel = new MyListDataBaseModel();
mylistDataBaseModel.setItemId(0);
mylistDataBaseModel.setItemName("");
mylistDataBaseModel.setItemPrice(0.0);
mylistDataBaseModel.setItemGst(0.0);
mylistDataBaseModel.setCategoryId(0);
mylistDataBaseModel.setItemCategoryName("");
mylistDataBaseModel.setItemPicture("");
mylistDataBaseModel.setItemcount(0);
mylistDataBaseModel.setListName(createList.getText().toString().trim());
mylistDataBaseModel.setListItemcount(0);
mylistDataBaseModel.setItemisAdded(0);
// Log.d("==============", "====" + createList.getText().toString().trim());
sqLiteDatabase = sqlLiteController.getWritableDatabase();
SqliteController.addMyListNameToDataBase(sqLiteDatabase, mylistDataBaseModel);
sqlLiteController.close();
and opearation in database is
public static void addMyListNameToDataBase(SQLiteDatabase sqLiteDatabase, MyListDataBaseModel model) {
ContentValues contentValues = new ContentValues();
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN__ITEM_ID, model.getItemId());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_NAME, model.getItemName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_PRICE, model.getItemPrice());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_GST, model.getItemGst());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM__CATEGORY_ID, model.getCategoryId());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_CATEGORY_DESCRIPTION, model.getItemCategoryName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_PICTURE, model.getItemPicture());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_COUNT_ID, model.getItemcount());
Log.d("==============", "====" + model.getListName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_MY_LIST_NAME, model.getListName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_MY_LIST_COUNT, model.getListItemcount());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_IS_ADDED, model.getItemisAdded());
sqLiteDatabase.insert(SqliteItemsDataBase.NewUSerInfo.MYLIST_TABLE, null, contentValues);
System.out.println("Cart Summary one row has been inserted");
UserNotification.notify(Constants.NOTIFICATION_MY_LIST_ITEM_ADDED, null);
}
this is my get data from table method
public static ArrayList<MyListDataBaseModel> getMyListData(SQLiteDatabase db) {
ArrayList<MyListDataBaseModel> allMyLists = new ArrayList<>();
Cursor cursor = db.rawQuery("select * from " + SqliteItemsDataBase.NewUSerInfo.MYLIST_TABLE, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
int localId = cursor.getInt(0);
Log.d("list","====localId====="+localId);
int itemId = cursor.getInt(1);
Log.d("list","====itemId====="+itemId);
String itemName = cursor.getString(2);
Log.d("list","====itemName====="+itemName);
Double itemPrice = cursor.getDouble(3);
Log.d("list","====itemPrice====="+itemPrice);
Double itemGst = cursor.getDouble(4);
Log.d("list","====itemGst====="+itemGst);
int categoryId = cursor.getInt(5);
Log.d("list","====categoryId====="+categoryId);
String catName = cursor.getString(6);
Log.d("list","====catName====="+catName);
String itemPicture = cursor.getString(7);
Log.d("list","====itemPicture====="+itemPicture);
int itemsCount = cursor.getInt(8);
Log.d("list","====itemsCount====="+itemsCount);
String listName = cursor.getString(9);
Log.d("list","====listName====="+listName);
int listItemCount = cursor.getInt(10);
Log.d("list","====listItemCount====="+listItemCount);
int itemIsAdded = cursor.getInt(11);
Log.d("list","====itemIsAdded====="+itemIsAdded);
allMyLists.add(new MyListDataBaseModel(localId, itemId, itemName, itemPrice,
itemGst, categoryId, catName, itemPicture, itemsCount, listName, listItemCount, itemIsAdded));
} while (cursor.moveToNext());
}
}
cursor.close();
return allMyLists;
}
I did a mistake that I got the data with some other column id instead of respected column id . That's my mistake

"Attempted to access a cursor after it has been closed"

I cannot understand this problem. I have tried to get the solution from other stackoverflow questions but failed to get the solution. I was not getting this error before. However, now I don't know what's wrong with the code stated below. Please help me with this. I'm stuck with this problem.
public void getAlbumsLists() {
final Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
final String _id = MediaStore.Audio.Albums._ID;
final String album = MediaStore.Audio.Media.ALBUM;
final String album_name = MediaStore.Audio.AlbumColumns.ALBUM;
final String artist = MediaStore.Audio.AlbumColumns.ARTIST;
final String tracks = MediaStore.Audio.AlbumColumns.NUMBER_OF_SONGS;
// final String data=MediaStore.Audio.Albums.ALBUM_ID; // NO
// final String id1=MediaStore.Audio.Albums.ALBUM_ID;
final String tit = MediaStore.Audio.Albums.ALBUM; //NO
final String nam = MediaStore.Audio.Albums.ALBUM_KEY; // NO
final String typ = MediaStore.Audio.Media.MIME_TYPE; // NO
final String art = MediaStore.Audio.Albums.ALBUM_ART; //<<<< CAN GET
final String artstkey = MediaStore.Audio.Artists.ARTIST_KEY; //<<<< CAN GET
final String frstyr = MediaStore.Audio.AlbumColumns.FIRST_YEAR; //<<<< CAN GET
final String lstyr = MediaStore.Audio.AlbumColumns.LAST_YEAR; //<<<< CAN GET
final String artstid = "artist_id"; //<<<< CAN GET
final String[] columns = {"*"};
Cursor cursor = getActivity().getContentResolver().query(uri, columns, null, null, null);
// Lists the columns in the cursor
for (String s : cursor.getColumnNames()) {
Log.d("COLUMNS", "Column = " + s);
}
while (cursor.moveToNext()) {
String id = (cursor.getString(cursor.getColumnIndex(_id)));
String name = cursor.getString(cursor.getColumnIndex(album_name));
String artist2 = cursor.getString(cursor.getColumnIndex(artist));
String nr = cursor.getString(cursor.getColumnIndex(tracks));
String x = (cursor.getString(cursor.getColumnIndex(album)));
//String data1=cursor.getString(cursor.getColumnIndexOrThrow(data)); //<<<< NOT A COLUMN
// String id2=cursor.getString(cursor.getColumnIndex(data));
//String title=cursor.getString(cursor.getColumnIndex(tit)); //<<<< NOT A COLUMN
//String name1=cursor.getString(cursor.getColumnIndex(nam)); //<<<< NOT A COLUMN
//String type=cursor.getString(cursor.getColumnIndex(typ)); //<<<< NOT A COLUMN
// AVAIALABLE COLUMNS
String artwork = cursor.getString(cursor.getColumnIndex(art)); //<<<< ADDED
String artistkey = cursor.getString(cursor.getColumnIndex(artstkey)); //<<<< ADDED
String artistid = cursor.getString(cursor.getColumnIndex(artstid)); //<<<< ADDED
String minyear = cursor.getString(cursor.getColumnIndex(frstyr));
String maxyear = cursor.getString(cursor.getColumnIndex(lstyr));
s = new albumInfo(id, name, artist2, nr, artwork, x); // EXCLUDED
albumList.add(s);
cursor.close();
recyclerView1.setAdapter(albumAdapter); // EXCLUDED
}
}
Move cursor.close(); outside the while loop.
Edited..
First time after the while loop iterates the cursor is closed so you need to put it outside while.
I can suggest three improvement scenarios.
You need to move the cursor to first before accessing it for fetching data from the cursor.
You need to close the cursor when nothing is returned or the cursor is null.
Move the cursor close outside of your while loop.
So I would like to recommend you to rewrite the code like following.
// After you have fetched the data from cursor
if(cursor == null) return;
if(cursor.size() == 0) {
cursor.close();
return;
}
for (String s : cursor.getColumnNames()) {
Log.d("COLUMNS", "Column = " + s);
}
// Move the cursor to the first position.
cursor.moveToFirst();
do {
String id = (cursor.getString(cursor.getColumnIndex(_id)));
String name = cursor.getString(cursor.getColumnIndex(album_name));
String artist2 = cursor.getString(cursor.getColumnIndex(artist));
String nr = cursor.getString(cursor.getColumnIndex(tracks));
String x = (cursor.getString(cursor.getColumnIndex(album)));
// ... Other code
} while (cursor.moveToNext());
recyclerView1.setAdapter(albumAdapter); // EXCLUDED
// Move the cursor outside of while loop
cursor.close();

get row numbers for a cursor

From my table I want to get the number of each row. For example, if I have 5 rows, I want to get 1,2,3,4,5.
I have this method, but I get only the number 1:
private void listaAvvio() {
SQLiteDatabase db = new DatabaseHelper(getActivity()).getReadableDatabase();
final List<Dettaglio1> dettagli1 = new ArrayList<Dettaglio1>();
String tabella_op = "SELECT .....";
Cursor cur = db.rawQuery(tabella_op, null);
while (cur.moveToNext()) {
Dettaglio1 d1 = new Dettaglio1();
d1.id = cur.getString(0);
d1.FIELD1= cur.getString(1);
d1.FIELD2= cur.getString(2);
d1.FIELD3= cur.getString(3);
d1.NUMBER_OF_SINGLE_ROW++;
dettagli1.add(d1);
}
cur.close();
db.close();
...
}
You are creating a new Dettaglio1 object in every loop iteration, so the NUMBER_OF_SINGLE_ROW in that object is always the same.
You have to use a separate variable to remember the row number:
int row_no = 0;
while (cur.moveToNext()) {
Dettaglio1 d1 = new Dettaglio1();
d1.id = cur.getString(0);
...
row_no++;
d1.NUMBER_OF_SINGLE_ROW = row_no;
dettagli1.add(d1);
}

Android Sqlite Transaction and Content Provider

I'm Parsing a JSON WebService and creating a array with data to INSERT and DELETE entries in a database.
I found the solution bulkInsert to insert multiple rows using database transactions inside a content provider, however, I am trying to do the same procedure to delete multiple lines.
The INSERT solution:
#Override
public int bulkInsert(Uri uri, ContentValues[] allValues) {
SQLiteDatabase sqlDB = mCustomerDB.getWritableDatabase();
int numInserted = 0;
String table = MyDatabase.TABLE;
sqlDB.beginTransaction();
try {
for (ContentValues cv : allValues) {
//long newID = sqlDB.insertOrThrow(table, null, cv);
long newID = sqlDB.insertWithOnConflict(table, null, cv, SQLiteDatabase.CONFLICT_REPLACE);
if (newID <= 0) {
throw new SQLException("Error to add: " + uri);
}
}
sqlDB.setTransactionSuccessful();
getContext().getContentResolver().notifyChange(uri, null);
numInserted = allValues.length;
} finally {
sqlDB.endTransaction();
}
return numInserted;
}
Using this call:
mContext.getContentResolver().bulkInsert(ProviderMyDatabase.CONTENT_URI, valuesToInsertArray);
Is there any way to delete multiple rows (with this array ID's) of database using content provider.
UPDATE:
I found this solution, using the `IN clause:
List<String> list = new ArrayList<String>();
for (ContentValues cv : valuesToDelete) {
Object value = cv.get(DatabaseMyDatabase.KEY_ROW_ID);
list.add(value.toString());
}
String[] args = list.toArray(new String[list.size()]);
String selection = DatabaseMyDatabase.KEY_ROW_ID + " IN(" + new String(new char[args.length-1]).replace("\0", "?,") + "?)";
int total = mContext.getContentResolver().delete(ProviderMyDatabase.CONTENT_URI, selection, args);
LOGD(TAG, "Total = " + total);
The problem is that, if the JSON return more than 1000 rows to insert, occurs error, because the SQLITE_MAX_VARIABLE_NUMBER is set to 999. It can be changed but only at compile time.
ERROR: SQLiteException: too many SQL variables
Thanks in advance
I solved this issue with this code:
if (!valuesToDelete.isEmpty()) {
StringBuilder sb = new StringBuilder();
String value = null;
for (ContentValues cv : valuesToDelete) {
value = cv.getAsString(kei_id);
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(value);
}
String args = sb.toString();
String selection = kei_id + " IN(" + args + ")";
int total = mContext.getContentResolver().delete(uri, selection, null);
LOGD(TAG, "Total = " + total);
} else {
LOGD(TAG, "No data to Delete");
}
Thanks
User ContentResolver object to delete multiple rows.
// get the ContentResolver from a context
// if not from any activity, then you can use application's context to get the ContentResolver
// 'where' is the condition e.g., "field1 = ?"
// whereArgs is the values in string e.g., new String[] { field1Value }
ContentResolver cr = getContentResolver();
cr.delete(ProviderMyDatabase.CONTENT_URI, where, whereArgs);
So any row with (field1 = field1Value) will be deleted.
If you want to delete all the rows then
cr.delete(ProviderMyDatabase.CONTENT_URI, "1 = 1", null);

Android - SQLite Column does not exist from certain page

I'm messing around with some SQLite databases for an Android app. I have a 'player' table with several players, and a one-to-many 'skill' table which has each player's skill points, like Shooting and Rebounding.
I have one activity in the app for actually filling out textboxes and inserting a player into the database. When the user hits the 'Add Player' button, a row is inserted into the 'player' table and a row is inserted into the 'skills' table which has a foreign key that references the 'player' table. After these inserts, I did a query to check if I could read the 'Shooting' value from the 'skills' table and put it in a Toast notification. That worked fine, and the code I used is here:
SQLiteDatabase db2 = dbHelper.getReadableDatabase();
String[] projection = { "shooting" };
String sortOrder = "shooting" + " DESC";
Cursor c = db2.query(
"skills", // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
c.moveToFirst();
int shooting = c.getInt(c.getColumnIndexOrThrow("shooting"));
Toast.makeText(this, "" + shooting, Toast.LENGTH_SHORT).show();
After I saw that this was working, I commented it out and put in an Intent to make the app switch to the 'Roster' activity after the player and skills are inserted. On the 'Roster' activity, I want to get each player's 'Shooting' skill. When I use the exact same code from above (which works from the other activity) I get an error which says:
06-16 15:59:42.602: E/AndroidRuntime(31537): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.silverray.messaround/com.silverray.messaround.Roster}: java.lang.IllegalArgumentException: column 'shooting' does not exist
I can't figure out why it's saying the 'shooting' column doesn't exist when I know I included it in my SQL Create statement, and I was even able to read this exact same column with the same code from another activity.
Thanks for reading. Any ideas?
EDIT: This is the full code for the Roster activity:
public class Roster extends Activity {
int teamID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_roster);
// CHECK ROSTER
DatabaseContract dbContract = new DatabaseContract();
DatabaseContract.DbHelper dbHelper = dbContract.new DbHelper(this);
SQLiteDatabase dbCheck = dbHelper.getReadableDatabase();
Intent intent = getIntent();
int ID = intent.getIntExtra("ID", 1);
teamID = ID;
String stringID = String.valueOf(ID);
String[] projection = { "_id, playerFirstName, playerLastName, playerPosition" };
String sortOrder = "playerFirstName" + " ASC";
Cursor c = dbCheck.query(
"player",
projection,
null,
null,
null,
null,
sortOrder
);
c.moveToFirst();
int rowsAffected = c.getCount();
if (rowsAffected < 1) {
TextView rosterList = (TextView) findViewById(R.id.txtListRoster);
rosterList.setText("Your team doesn't have any players!");
c.close();
dbCheck.close();
} else {
String players = "";
for (int l = 0; l < rowsAffected; l++) {
String playerName = c.getString(c.getColumnIndexOrThrow("playerFirstName"));
String playerLastName = c.getString(c.getColumnIndexOrThrow("playerLastName"));
String position = c.getString(c.getColumnIndexOrThrow("playerPosition"));
int playerID = c.getInt(c.getColumnIndexOrThrow("_id"));
String player_ID = String.valueOf(playerID);
String pos = "";
if (position.equals("Point Guard")) {
pos = "PG";
} else if (position.equals("Shooting Guard")) {
pos = "SG";
} else if (position.equals("Small Forward")) {
pos = "SF";
} else if (position.equals("Power Forward")) {
pos = "PF";
} else if (position.equals("Center")) {
pos = "C";
}
SQLiteDatabase db2 = dbHelper.getReadableDatabase();
String[] projection2 = { "shooting" };
String sortOrder2 = "shooting" + " DESC";
Cursor c2 = db2.query(
"skills",
projection2,
null,
null,
null,
null,
sortOrder2
);
c2.moveToFirst();
//** Everything works until this line:
int shooting = c2.getInt(c.getColumnIndexOrThrow("shooting"));
players += playerName + " " + playerLastName + " (" + pos + ") Shooting: ";
if (l != (rowsAffected - 1)) {
players += "\n";
}
TextView rosterList = (TextView) findViewById(R.id.txtListRoster);
rosterList.setText(players);
if (l != (rowsAffected - 1)) {
c.moveToNext();
}
c2.close();
}
c.close();
dbCheck.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.roster, menu);
return true;
}
public void addPlayer(View view) {
Intent goToAddPlayer = new Intent(this, AddPlayer.class);
goToAddPlayer.putExtra("ID", teamID);
this.startActivity(goToAddPlayer);
this.finish();
return;
}
}
int shooting = c2.getInt(c.getColumnIndexOrThrow("shooting"));
should be
int shooting = c2.getInt(c2.getColumnIndexOrThrow("shooting"));
You are now working on 2nd query but trying to get column index from 1st.

Categories

Resources