1

im trying to get the data from a table then add it to another table. i need the KEY_CATEGORYIDwhich auto increments from table 1 and then i need to add it to table 2 and 4. i cant figure out how to do this as KEY_CATEGORYID will only have a value after the createBudget method has finished and that happens after addId is finished this has me completely stumped on what to do any help is greatly appreciated.

public SQLiteDatabase createBudget(String bname, String bpay, String bamount,
                String bmemo) {
            // TODO Auto-generated method stub
            ContentValues t1 = new ContentValues();
            ContentValues t2 = new ContentValues();
            ContentValues t4 = new ContentValues();
            t1.put(KEY_NAME, bname);
            t1.put(KEY_PAYDAY,bpay);
            t2.put(KEY_AMOUNT, bamount);
            t2.put(KEY_DATE, date);
            t4.put(KEY_MEMO, bmemo);
            t4.put(KEY_DATE,date);

            ourDatabase.insert(DATABASE_TABLE1, null, t1);
            ourDatabase.insert(DATABASE_TABLE2, null, t2);
            ourDatabase.insert(DATABASE_TABLE4, null, t4);
            addID(bname);
        return ourDatabase;
        }
    private void addID(String bname) throws SQLException {
                // TODO Auto-generated method stub
                ContentValues num = new ContentValues();
                List<String> nums = new ArrayList<String>();
                int number = 0;
                String[] columns = new String[]{KEY_CATEGORYID};        
                Cursor c = ourDatabase.query(DATABASE_TABLE1, columns,KEY_CATEGORYID + "=?", new String[] {String.valueOf(bname)}, null, null, null, null);
                if(c!= null)
                {
                    if (c.moveToFirst()) { 
                        nums.add(c.getString(0));
                        number = nums.get(0);
                        }
                    num.put(KEY_CATEGORYID, number);
                }
                ourDatabase.insert(DATABASE_TABLE2, null, num);
                ourDatabase.insert(DATABASE_TABLE4, null, num);
            }
  • http://stackoverflow.com/questions/9109438/how-to-use-an-existing-database-with-an-android-application/9109728#9109728 – Yaqub Ahmad Nov 19 '12 at 16:02

1 Answers1

0

The insert method returns the autogenerated key value:

long key = ourDB.insert(TABLE1, null, t1);
t2.put(KEY_CATEGORYID, key);
ourDB.insert(TABLE2, null, t2);
CL.
  • 173,858
  • 17
  • 217
  • 259