I'm trying to load a database column with a cursor result for my quiz app. The reason for this is that i want to populate a list view with the questions in a each category so i set up this:
public void putValues(){
for (int i = 0; i < 18; i++) {
Cursor contentCursor = null;
contentCursor = mDB
.rawQuery("select count(*) from questions_en where used = 0 and category" + " = " + i, null);
if(contentCursor.getCount() >0 )
contentCursor.moveToFirst();
if (contentCursor.isAfterLast()) {
contentCursor.close();
mDB.close();
return;
}
int contentCursorInt = contentCursor.getInt(0);
Cursor upateCursor = null;
upateCursor = mDB.rawQuery("update categories_en set questions_count" + " = " + contentCursorInt + " where " + "_id" + " = " + i, null);
upateCursor.moveToNext();
upateCursor.close();
contentCursor.close();
}
}
so that when the user clicks an answer (on the question screen) used becomes 1(or any non-zero value) the query result changes. The above code works fine the very first time. Because i haven't set up the question screen, i added this query:
public void test(){
Cursor cus = mDB.rawQuery("update questions_en set used = 1 where category = 2 and _id = 146", null);
cus.close();
}
to my DB Adapter and then called this method from my MainActivty
#Override
public void onClick(View v) {
TestAdapter mTest = new TestAdapter(MainActivity.this);
mTest.createDatabase();
mTest.open();
mTest.test();
Log.d(DBHelper.TAG, " Worked ");
mTest.close();
}
});
But when i click on this and go to my ListActivity I expected the value of category 2 to have changed since the query had just been carried out again. But it doesn't reduce. I pulled out my DB from DDMS(file explorer) and i found out that the query to _id = 146 actually didn't change used to 1. Any help on what may be the cause?
Solve the problem with the help of this.
I just changed this:
public void test(){
Cursor cus = mDB.rawQuery("update questions_en set used = 1 where category = 2 and _id = 146", null);
cus.close();
}
to this
public void test(){
int id = 3;
ContentValues data = new ContentValues();
data.put(DBHelper.KEY_USED, "1");
mDB.update(DBHelper.KEY_QUESTIONS_TABLE, data, DBHelper.KEY_ID + " = " + id , null);
}
Related
I m trying to delete the row from input for GoalWeight, Goal Date and Current Weight. It is not erroring but the row is not getting delete.
DeleteLayout
Button deleteB;
DatabaseHelper myDB;
EditText goalD;
EditText goalW;
EditText currentW;
Intent j;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.deletelayout);
deleteB = findViewById(R.id.buttonDelete);
myDB = new DatabaseHelper(this);
deleteB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goalD = findViewById(R.id.goaldinput2);
goalW = findViewById(R.id.goalwinput3);
currentW = findViewById(R.id.currentWinput2);
if(goalD.length() !=0 && goalW.length() !=0 && currentW.length() !=0){
Toast.makeText(DeleteLayout.this,"Goal Date: " +goalD.getText().toString()+ "Goal Weight: " + goalW.getText().toString()+
"Current Weight: " +currentW.getText().toString()+ " entered.",
Toast.LENGTH_LONG).show();
myDB.deleteContent(goalD.getText().toString(), goalW.getText().toString(), currentW.getText().toString());
j = new Intent(DeleteLayout.this, historyActivity.class);
startActivity(j);
}
else{
Toast.makeText(DeleteLayout.this,"All data not entered.", Toast.LENGTH_LONG).show();
}
}
});
Delete method in DatabaseHelper
public void deleteContent(String goalDate, String goalWeight,String currentWeight){
SQLiteDatabase db = this.getWritableDatabase();
String query = " DELETE FROM " + TABLE_NAME + "WHERE GDATE = "+
goalDate + " AND " + "GWEIGHT = " + goalWeight + " AND " + "CWEIGHT = " + currentWeight ;
}
The main problem (not the only one) is that inside deleteContent(), although you create the SQL statement, you never execute it by say execSQL().
So no attempt is made to delete any row.
However you should change so to use the delete() method, like this:
public int deleteContent(String goalDate, String goalWeight, String currentWeight){
SQLiteDatabase db = this.getWritableDatabase();
String where = "GDATE = ? AND GWEIGHT = ? AND CWEIGHT = ?";
int rows = db.delete(TABLE_NAME, where, new String[] {goalDate, goalWeight, currentWeight});
db.close();
return rows;
}
This is the recommended way, because it is safe and it also returns the number of rows affected/deleted (which you can examine to check if the deletion was successful).
So you can use it like this:
int rows = myDB.deleteContent(
goalD.getText().toString(),
goalW.getText().toString(),
currentW.getText().toString()
);
and in the variable rows you will have the number of the deleted rows.
I made SQL database and populated it with values. In TextView I need to show multiply result of specific rows.
I made SQL statement and I hope that is correct.
public List<Food> multiplyFat(){
String totalFat = "SELECT " +FoodEntry.COLUMN_FAT_TOTAL + " FROM " + FoodEntry.TABLE_NAME + " WHERE ( "
+FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + " ) > 0";
SQLiteDatabase db = this.getWritableDatabase();
List<Food> storeTotalFat = new ArrayList<>();
Cursor cursor = db.rawQuery(totalFat, null);
if (cursor.moveToFirst()){
do {
double fat = Double.parseDouble(cursor.getString(0));
storeTotalFat.add(new Food(fat));
} while (cursor.moveToNext());
}
cursor.close();
return storeTotalFat;
}
To be more clear I need to multiply values from row COLUMN_FAT_TOTAL with row COLUMN_GRAM and display result into the TextView. Or should I put these SQL statement:
String totalFat = "SELECT " +FoodEntry.COLUMN_FAT_TOTAL + " * " +FoodEntry.COLUMN_GRAM + " FROM " +FoodEntry.TABLE_NAME;
That is simplier way but I am not sure that it is correct way.
Anyhow I need to display this multiplyFat() function (result) into TextView. Any help or advice would be really helpfull.
public List multiplyFat(){
String totalFat = "SELECT " +FoodEntry.COLUMN_FAT_TOTAL + " FROM " + FoodEntry.TABLE_NAME + " WHERE ( "
+FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + " ) > 0";
The above works perfectly in MySQL, I just tried it.
SQLiteDatabase db = this.getWritableDatabase(); --> db = this.getReadableDatabase();
Since you are not changing anything in the SQLite database you want a '.getReadableDatbase();' not '.getWritableDatabase();'
List<Food> storeTotalFat = new ArrayList<>();
Cursor cursor = db.rawQuery(totalFat, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
do {
double fat = Double.parseDouble(cursor.getString(0));
storeTotalFat.add(new Food(fat));
} cursor.moveToNext();
}
cursor.close();
return storeTotalFat;
}
See how I first moved to the first index, then I ask it to continue in a while loop until it has reached the final element in the SQL results. Your way was not actually incrementing the cursor, it would have only been able to add the first result to the storeTotalFat ArrayList.
-------- part 2 ---------
Now let's pretend we are back in the activity, woo!
Let's say there is a class variable reference to the database helper and add a new ArrayList to house the results from the query result we just gained.
DBHelper myDBhelper = DBHelper.getInstance(MainActivity.this)
ArrayList<String> sqlResultArray = new ArrayList<>();
If you want a Recyclerview you make a separate RviewAdapter class, in your case FoodFatRecyclerViewAdapter and add the following
RecyclerView rv = (RecyclerView) findViewById(R.id.foodFatRecView);
LinearLayoutManager llm = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(llm);
FoodFatRecyclerViewAdapter foodFatAdapter = new FoodFatRecyclerViewAdapter(MainActivity.this, sqlResultArray);
rv.setAdapter(foodFatAdapter);
Now as for the adding of the result to the textview create a new class called FoodFatRecyclerViewAdapter
public class FoodFatRecyclerViewAdapter extends RecyclerView.Adapter<FoodFatViewHolder> {
ArrayList<String> mFoodFatItems;
Context mContext;
public FoodFatRecyclerViewAdapter(Context context, ArrayList<String> array) {
mContext = context;
mFoodFatItems = array;
}
#Override
public FoodFatViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.this_xml_layout_will_describe_the_arrangement_of_the_indi_item_in_the_list_not_the_master_view, parent, false);
FoodFatViewHolder recyclerView = new FoodFatViewHolder(view);
return recyclerView;
}
#Override
public void onBindViewHolder(FoodFatViewHolder holder, final int position) {
holder.mFatTotalTextView.setText(mFoodFatItems.get(position));
}
#Override
public int getItemCount() {
return mFoodFatItems.size();
}
}
Now the final piece to the puzzle, the View Holder so create a class called FoodFatViewHolder
public class FoodFatViewHolder extends RecyclerView.ViewHolder{
TextView mFatTotalTextView;
public FoodFatViewHolder(View itemView) {
super(itemView);
mFatTotalTextView = (TextView) itemView.findViewById(R.id.the_textview_id_within_the_individ_item_in_rv_xml_layout);
}
}
Voila! It should work
You need to show the multiplication total then you shouldn't do a select on COLUMN_FAT_TOTAL. Instead you should do the computation in your select query and store that computation in an alias. You can then use that alias as a result.
Modify your query as below
String totalFat = "SELECT " +FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + "AS Result FROM " + FoodEntry.TABLE_NAME";
You are on the right track. Do the math in the database if it is easy and straight forward, which this example is.
Might I suggest the following (similar to kapsym answer) for your sql statement:
String totalFat = "SELECT " + FoodEntry.COLUMN_FAT_TOTAL + ", " + FoodEntry.COLUMN_GRAM + "," FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + "AS TotalFat FROM " + FoodEntry.TABLE_NAME + " WHERE ( " + FoodEntry.COLUMN_FAT_TOTAL + " * " + FoodEntry.COLUMN_GRAM + " ) > 0";
You should study the basics of MySQL : https://www.tutorialspoint.com/mysql/mysql-select-query.htm
After the SELECT, you add column names that you want to retrieve and not expressions.
For your case, Use this Query to get all fat_total & gram entries :
String totalFat = "SELECT " + FoodEntry.COLUMN_FAT_TOTAL + "," + FoodEntry.COLUMN_GRAM + " FROM " + FoodEntry.TABLE_NAME;
Then you retrieve fatTotal * gram for each cursor, multiply it and feed it into your storeTotalFat array based on (!= 0) condition.
Cursor cursor = db.rawQuery(totalFat, null);
if (cursor.moveToFirst()){
do {
double fat = Double.parseDouble(cursor.getString(0));
double gram= Double.parseDouble(cursor.getString(1));
if (fat * gram != 0)
storeTotalFat.add(new Food(fat * gram));
} while (cursor.moveToNext());
}
I have a ListView with items that are added dynamically. When an item is added, it is added to the ListView and also inserted into a SQLite Database so that the items in the list can be saved. I can also remove specific items by getting the postion if the item and then removing it with that information.
This is how I add items (I use multiple classes):
In DataModel.class:
public void addItem(Object data) {
String string = String.valueOf(data);
mPlanetsList.add(createPlanet("planet", string));
History history = new History();
history.getDataHashMap().put("planet", data);
history.addToHistoryDB();
mHistoryList.add(history);
if (null != mOnItemAddHandler) {
mOnItemAddHandler.onItemAdded(data);
}
}
In History.class:
public void addToHistoryDB() {
MySQLiteOpenHelper mDbHelper = MySQLiteOpenHelper.getInstance();
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = getContentValues();
rawId = (int) db.insert(TABLE_NAME, COL_ID, values);
db.close();
}
This is how I remove items:
In DataModel.class:
public void removeItem(int index) {
if (mPlanetsList == null || index < 0 || index >= mPlanetsList.size()) {
return;
}
// remove from mPlanetList
mPlanetsList.remove(index);
History history = mHistoryList.get(index);
mHistoryList.remove(index);
if (null != history) {
history.remove();
history = null;
}
// notify, the HistoryFragment will update view
if (null != mOnItemAddHandler) {
mOnItemAddHandler.onItemRemove(index);
}
In History.class:
public void remove() {
MySQLiteOpenHelper mDbHelper = MySQLiteOpenHelper.getInstance();
SQLiteDatabase db = mDbHelper.getWritableDatabase();
int r = db.delete(TABLE_NAME, "_id = ?", // delete the int r ??
new String[] { String.valueOf(rawId) });
db.close();
}
When the app in removed from the 'recent apps' or is restarted, initList() is called which restored the ListView items from the Database.
This is the code:
DataModel:
private void initList() {
mHistoryList = History.getList();
for (int i = 0; i < mHistoryList.size(); i++) {
Object obj = mHistoryList.get(i).getDataHashMap().get("planet");
mPlanetsList.add(createPlanet("planet", String.valueOf(obj)));
}
}
History:
public static ArrayList<History> getList() {
Cursor cursor = null;
try {
MySQLiteOpenHelper mDbHelper = MySQLiteOpenHelper.getInstance();
SQLiteDatabase db = mDbHelper.getWritableDatabase();
String sql = "select * from " + History.TABLE_NAME;
ArrayList<History> list = new ArrayList<History>();
cursor = db.rawQuery(sql, null);
if (cursor != null) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
History item = new History();
item.fromCuror(cursor);
list.add(item);
}
}
return list;
} finally {
if (null != cursor && Integer.parseInt(Build.VERSION.SDK) < 14) {
cursor.close();
}
}
}
This method works fine as long as the order of the list is not changed - I can add items and removes items and it all works perfectly. However, I would like items to be added to the top of the list rather than the bottom.
So I read around on how to add items to the top of a ListView and found that by adding a 0 as the position when adding the item, the new items go to the top of the list.
mPlanetsList.add(0, createPlanet("planet", string)); // I put the 0 in wherever the item is added eg when adding from the database
When I do this, however, the items viewed/deleted in the ListView do not continue to correspond with the data in the Database. For example, Lets say I add three items to the List: dog then cat then horse. The ListView shows them in the correct order (horse at the top). If I then delete an item, lets say: cat , the ListView updates and everyting is good. But if I then restart the app, initList() is called. This is where the problem occurs - It is not cat that is removed from the list, it is horse or dog.
Possible points where I think the problem could be:
a) in the initList() - It is not adding the correct items
b) in the removeItem() - It is not removing the correct items from the Database.
c) in the getList() - maybe something with the cursor???
This think b) is more likely but I don't know where the problem is exactly or what to change it too.
EDIT:
After a little testing, I found that I was right that b) is where it goes wrong.
The steps to reproduce:
Create three items: cat then dog then horse. The ListView shows them in the correct order ie horse at the top, cat at the bottom. The Database shows them with cat at the top, horse at the bottom.
When I delete horse (top of ListView, bottom of Database) the ListView updates correctly, but in the Database it is not horse that has been deleted but in fact cat.
So because of the wrong removal, when the Database is used to restore the ListView, the ListView appears wrong.
I hope this makes things clearer!
EDIT 2: This is how I create my table:
public static final String TABLE_NAME = "history_table";
public static final String COL_TITLE = "title";
public static final String COL_CONTENT = "content";
public static final String COL_DATE = "date";
public static final String COL_TYPE = "type";
public static final String COL_ONGOING = "ongoing";
public static final String COL_DATA = "data";
public static final String COL_ID = "_id";
public static final String DATABASE_CREATE = "create table " + TABLE_NAME
+ "(" + COL_ID + " integer primary key autoincrement, " + COL_TITLE
+ " text not null, " + COL_CONTENT + " text not null, " + COL_DATE
+ " text not null, " + COL_TYPE + " text not null, " + COL_ONGOING
+ " text not null, " + COL_DATA + " text not null );";
This is getContentValues():
public ContentValues getContentValues() {
ContentValues values = new ContentValues();
values.put(History.COL_TITLE, "MyTitle");
values.put(History.COL_CONTENT, "MyContent");
values.put(History.COL_DATE, "Date placeholder");
values.put(History.COL_TYPE, "QuickNote");
values.put(History.COL_ONGOING, "Ongoing placeholder");
values.put(History.COL_DATA, new JSONObject(mDataHashMap).toString());
return values;
}
EDIT 3:
I have basically narrowed it down to the fact that because the order of items in the ListView and in the Database are different, deleting items by their postition in the list does not work. So would a possible solution would be to invert the order of items in the database to match the ListView (good idea / possible ?).
EDIT 3.1:
https://stackoverflow.com/a/7348117/2442638
This order by descending may help. I don't know where I should put it though
EDIT 3.5:
I now have the ordering working. The deleting very nearly works, but there is now a problem that the first deletion doesn't work. The rest work after that. I am sorting by the _id and as that is autoincrement maybe it starts at 1 or 0 and the list starts at the other. I will do more research
There are two list in the app: mHistoryList and mPlanetsList, You should keep the order of the data itmes in them are the same.
You can add items to the top of listview by calling the method addItem in DataModel:
public void addItem(Object data) {
History history = new History();
history.getDataHashMap().put("planet", data);
history.addToHistoryDB();
mHistoryList.add(0, history);
mPlanetsList.add(0, history.createPlanet());
if (null != mOnItemAddHandler) {
mOnItemAddHandler.onItemAdded(data);
}
}
Then the new data will be at the top of the listview.
After app restart, the code below will be called:
private void initList() {
mHistoryList = History.getList();
for (int i = 0; i < mHistoryList.size(); i++) {
mPlanetsList.add(mHistoryList.get(i).createPlanet());
}
}
We should make sure the data from History.getList(); has the same order, in another word, the new data time in the head of the list.
So we should change the code to (order by _id desc):
public static ArrayList<History> getList() {
Cursor cursor = null;
try {
MySQLiteOpenHelper mDbHelper = MySQLiteOpenHelper.getInstance();
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// order by _id desc
String sql = "select * from " + History.TABLE_NAME + " order by _id desc";
ArrayList<History> list = new ArrayList<History>();
cursor = db.rawQuery(sql, null);
if (cursor != null) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
History item = new History();
item.fromCuror(cursor);
list.add(item);
}
}
return list;
} finally {
if (null != cursor && Integer.parseInt(Build.VERSION.SDK) < 14) {
cursor.close();
}
}
}
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.
I am trying, unsucessfully, to query my database to find the maximum 'area number', in my areas table for a certain inspection, so that I can set the text in a form to the next area number.
The database table consists of four columns; _id, inpsection_link, area_number, area-reference.
I have created the following in my database helper class (using this post as a guide: SQLiteDatabase.query method):
public int selectMaxAreaNumber (long inspectionId) {
String inspectionIdString = String.valueOf(inspectionId);
String[] tableColumns = new String[] {
AREA_NUMBER,
"(SELECT max(" + AREA_NUMBER + ") FROM " + AREAS_TABLE + ") AS max"
};
String whereClause = INSPECTION_LINK + " = ?";
String[] whereArgs = new String[] {
inspectionIdString
};
Cursor c = rmDb.query(AREAS_TABLE, tableColumns, whereClause, whereArgs,
null, null, null);
int maxAreaNumber = c.getColumnIndex("max");
return maxAreaNumber;
}
Which I then call in the areaEdit class as follows:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rmDbHelper = new RMDbAdapter(this);
rmDbHelper.open();
Intent i = getIntent();
inspectionId = i.getLongExtra("Intent_InspectionID", -1);
areaId = i.getLongExtra("Intent_AreaID", -1);
if (areaId == -1) {
nextAreaNumber = rmDbHelper.selectMaxAreaNumber(inspectionId) + 1;
Toast.makeText(getApplicationContext(), String.valueOf(nextAreaNumber),
Toast.LENGTH_LONG).show();
}
setContentView(R.layout.edit_area);
setUpViews();
populateFields();
setTextChangedListeners();
}
However, it just returns 1 everytime (even if there are numbers higher than that stored in the database).
Confused.com!! Any help much appreciated.
Your issue is here :
int maxAreaNumber = c.getColumnIndex("max");
You're getting the column index of max, which is 1 because you only have one column in your query.
Instead, do something like this :
int maxAreaNumber = 0;
if(c.moveToFirst())
{
maxAreaNumber = c.getInt(1);
// or cleaner
maxAreaNumber = c.getInt(c.getColumnIndex("max"));
}
else
// no data in cursor