I know this question has been asked several times, but I just can't get the right syntax for my problem.
I want to sum my value of "einnahmen".
This is my SqlDbHelper class:
public class SqlDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_TABLE = "PHONE_CONTACTS";
public static final String COLUMN1 = "nr";
public static final String COLUMN2 = "name";
public static final String COLUMN3 = "einnahmen";
public static final String COLUMN4 = "ausgaben";
public static final String COLUMN5 = "datum";
private static final String SCRIPT_CREATE_DATABASE =
"create table "+ DATABASE_TABLE
+ " (" + COLUMN1+ " integer primary key autoincrement, "
+ COLUMN2+ " text not null, "
+ COLUMN3 + " text not null, "
+ COLUMN4 + " text not null, "
+ COLUMN5 + " text not null);";
public SqlDbHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
This is my MainActivity:
public class BookActivity extends Activity {
SqlHandler sqlHandler;
ListView lvCustomList;
EditText etName, etEinnahmen, etAusgaben, etDatum;
ImageButton btn_add;
TextView gesamteinnahmen;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
gesamteinnahmen = (TextView) findViewById(R.id.tVgesamtEinnahmen);
lvCustomList = (ListView) findViewById(R.id.lv_custom_list);
etName = (EditText) findViewById(R.id.et_name);
etEinnahmen = (EditText) findViewById(R.id.et_einnahmen);
etAusgaben = (EditText) findViewById(R.id.et_ausgaben);
etDatum = (EditText) findViewById(R.id.et_datum);
btn_add = (ImageButton) findViewById(R.id.btn_add);
sqlHandler = new SqlHandler(this);
showList();
btn_add.setOnClickListener(new OnClickListener() {
#SuppressLint("ShowToast")
#Override
public void onClick(View v) {
String name = etName.getText().toString();
String einnahmen = etEinnahmen.getText().toString();
String ausgaben = etAusgaben.getText().toString();
String datum = etDatum.getText().toString();
if (TextUtils.isEmpty(name)) {etName.setError("Das Feld ist leer");return;}
else if (TextUtils.isEmpty(einnahmen)) {etEinnahmen.setError("Das Feld ist leer");return;
} else if (TextUtils.isEmpty(ausgaben)) {etAusgaben.setError("Das Feld ist leer");return;
} else if (TextUtils.isEmpty(datum)) {etDatum.setError("Das Feld ist leer");return;
} else {
Toast.makeText(BookActivity.this,"Daten wurden erfolgreich gespeichert", Toast.LENGTH_SHORT).show();
String query = "INSERT INTO PHONE_CONTACTS(name,einnahmen,ausgaben,datum) values " +
"('" + name + "','" + einnahmen +"','" + ausgaben + "','" + datum + "')";
sqlHandler.executeQuery(query);
showList();
etName.setText("");
etEinnahmen.setText("");
etAusgaben.setText("");
etDatum.setText("");
}
}
});
}
private void showList() {
ArrayList contactList = new ArrayList();
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS";
Cursor c1 = sqlHandler.selectQuery(query);
if (c1 != null && c1.getCount() != 0) {
if (c1.moveToFirst()) {
do {
ContactListItems contactListItems = new ContactListItems();
contactListItems.setNr(c1.getString(c1.getColumnIndex("nr")));
contactListItems.setName(c1.getString(c1.getColumnIndex("name")));
contactListItems.setEinnahmen(c1.getString(c1.getColumnIndex("einnahmen")));
contactListItems.setAusgaben(c1.getString(c1.getColumnIndex("ausgaben")));
contactListItems.setDatum(c1.getString(c1.getColumnIndex("datum")));
contactList.add(contactListItems);
} while (c1.moveToNext());
}
}
c1.close();
ContactListAdapter contactListAdapter = new ContactListAdapter(
BookActivity.this, contactList);
lvCustomList.setAdapter(contactListAdapter);}
}
I hope this code helps you.
Your sql query should looks like
query = "SELECT *, SUM(einnahmen) as sum FROM PHONE_CONTACS";
in your SqlDbHelper class:
public long sumEinnahmen() {
SQLiteStatement statement = getReadableDatabase().compileStatement(
"select sum(" + COLUMN3 + " from " + DATABASE_TABLE);
try {
return statement.simpleQueryForLong();
} finally {
statement.close();
}
}
Note that your column is currently declared as a text column instead of as integer or real column. If you are only storing numeric data in that column, you should declare it with either of those numeric types instead.
Related
how to add second column value of same or other table in another spinner from sqlite database using button click in android studio
retrievebtn.setOnClickListener(arg0 -> {
// TODO Auto-generated method stub
nos.clear();
names.clear();
//OPEN
db.openDB();
//RETRIEVE
Cursor c = db.getAllValues();
c.moveToFirst();
while(!c.isAfterLast())
{
String no = c.getString(0);
nos.add(no);
String name = c.getString(1);
names.add(name);
c.moveToNext();
}
//CLOSE
c.close();
db.close();
//SET IT TO SPINNER
sp1.setAdapter(adapter);
sp2.setAdapter(adapter);
});
Perhaps consider the following working example.
This consists of 2 spinners and 3 buttons. The buttons controlling from which of the 3 tables the data is extracted for the 2nd spinner.
The trick, as such, used is to use AS to utilise a standard column name, irrespective of the actual column name. The one difference is that this rather than using a normal adapter, it utilises a CursorAdapter (SimpleCursorAdapter as it's quite flexible) and thus you can extract the data directly.
First the SQLite side i.e. the class that extends SQLiteOpenHelper :-
class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "the_database.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE1_TABLE = "_table1";
public static final String TABLE1_ID_COL = BaseColumns._ID;
public static final String TABLE1_NAME_COL = "_name";
public static final String TABLE1_DESC_COL = "_desc";
private static final String TABLE1_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE1_TABLE + "(" +
TABLE1_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE1_NAME_COL + " TEXT UNIQUE" +
"," + TABLE1_DESC_COL + " TEXT " +
");";
public static final String TABLE2_TABLE = "_table2";
public static final String TABLE2_ID_COL = BaseColumns._ID;
public static final String TABLE2_TABLE1_ID_MAP_COL = "_table1_id_map";
public static final String TABLE2_NAME_COL = "_name";
private static final String TABLE2_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE2_TABLE + "(" +
TABLE2_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE2_TABLE1_ID_MAP_COL + " INTEGER " +
"," + TABLE2_NAME_COL + " TEXT" +
");";
public static final String TABLE3_TABLE = "_table3";
public static final String TABLE3_ID_COL = BaseColumns._ID;
public static final String TABLE3_TABLE2_ID_MAP_COL = "_table2_id_map";
public static final String TABLE3_NAME_COL = "_name";
private static final String TABLE3_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS " + TABLE3_TABLE +"(" +
TABLE3_ID_COL + " INTEGER PRIMARY KEY" +
"," + TABLE3_TABLE2_ID_MAP_COL + " INTEGER " +
"," + TABLE3_NAME_COL + " TEXT " +
");";
private static volatile DBHelper INSTANCE;
private SQLiteDatabase db;
public static final String SPINNER_COLUMN1 = "_spc1";
public static final String SPINNER_COLUMN2 = "_spc2";
private DBHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
db = this.getWritableDatabase();
}
public static DBHelper getInstance(Context context) {
if (INSTANCE==null) {
INSTANCE = new DBHelper(context);
}
return INSTANCE;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE1_CREATE_SQL);
db.execSQL(TABLE2_CREATE_SQL);
db.execSQL(TABLE3_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long insertTable1Row(String name,String description) {
ContentValues cv = new ContentValues();
cv.put(TABLE1_NAME_COL,name);
cv.put(TABLE1_DESC_COL,description);
return db.insert(TABLE1_TABLE,null,cv);
}
public long insertTable2Row(String name, long table1_id) {
ContentValues cv = new ContentValues();
cv.put(TABLE2_NAME_COL,name);
cv.put(TABLE2_TABLE1_ID_MAP_COL,table1_id);
return db.insert(TABLE2_TABLE,null,cv);
}
public long insertTable3Row(String name, long table2_id) {
ContentValues cv = new ContentValues();
cv.put(TABLE3_NAME_COL,name);
cv.put(TABLE3_TABLE2_ID_MAP_COL,table2_id);
return db.insert(TABLE3_TABLE,null,cv);
}
public Cursor getSpinnerData(String table, long map) {
String[] columns = new String[]{};
String whereClause = "";
String[] whereArgs = new String[]{String.valueOf(map)};
switch (table) {
case TABLE1_TABLE:
columns = new String[]{TABLE1_ID_COL,TABLE1_NAME_COL + " AS " + SPINNER_COLUMN1,TABLE1_DESC_COL + " AS " + SPINNER_COLUMN2};
whereClause = "";
break;
case TABLE2_TABLE:
columns = new String[]{TABLE2_ID_COL ,TABLE2_NAME_COL + " AS " + SPINNER_COLUMN1,"'-' AS " + SPINNER_COLUMN2};
whereClause = TABLE2_TABLE1_ID_MAP_COL + "=?";
break;
case TABLE3_TABLE:
columns = new String[]{TABLE3_ID_COL, TABLE3_NAME_COL + " AS " + SPINNER_COLUMN1,"'~' AS " + SPINNER_COLUMN2};
whereClause = TABLE3_TABLE2_ID_MAP_COL + "=?";
break;
}
if (map < 0) {
whereClause="";
whereArgs = new String[]{};
}
if (columns.length > 0) {
return db.query(table,columns,whereClause,whereArgs,null,null,null);
} else {
return db.query(TABLE1_TABLE,new String[]{"0 AS " + TABLE1_ID_COL + ",'ooops' AS " + SPINNER_COLUMN1,"'ooops' AS " + SPINNER_COLUMN2},null,null,null,null,null,"1");
}
}
}
as said there are three tables
a singleton approach has been utilised for the DBHelper
the most relevant aspect in regards to switching spinner data is the getSpinnerData function, which takes two parameters, the most relevant being the first the tablename which drives the resultant query.
Note the use of BaseColumns._ID ALL Cursor adapters must have a column name _id (which is what BaseColumns._ID resolves to). The column should be an integer value that uniquely identifies the row.
the 2nd parameter caters for the selection of only related data, but a negative is used to ignore this aspect.
The Activity "MainActivity" used to demonstrate is :-
public class MainActivity extends AppCompatActivity {
Button btn1, btn2, btn3;
Spinner sp1,sp2;
String[] spinnerColumns = new String[]{DBHelper.SPINNER_COLUMN1,DBHelper.SPINNER_COLUMN2};
SimpleCursorAdapter sca1,sca2;
String sp1_table_name = DBHelper.TABLE1_TABLE;
String sp2_table_name = DBHelper.TABLE2_TABLE;
Cursor csr1, csr2;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = this.findViewById(R.id.button1);
btn2 = this.findViewById(R.id.button2);
btn3 = this.findViewById(R.id.button3);
sp1 = this.findViewById(R.id.spinner1);
sp2 = this.findViewById(R.id.spinner2);
dbHelper = DBHelper.getInstance(this);
Cursor test4Data = dbHelper.getWritableDatabase().query(DBHelper.TABLE1_TABLE,null,null,null,null,null,null, "1");
if (test4Data.getCount() < 1) {
addSomeData();
}
test4Data.close();
sp1_table_name = DBHelper.TABLE1_TABLE;
sp2_table_name = DBHelper.TABLE2_TABLE;
setUpButtons();
setOrRefreshSpinner1();
setOrRefreshSpinner2();
}
void setUpButtons() {
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE1_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE2_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sp2_table_name = DBHelper.TABLE3_TABLE;
setOrRefreshSpinner2();
setOrRefreshSpinner1();
}
});
}
void setOrRefreshSpinner1() {
csr1 = dbHelper.getSpinnerData(sp1_table_name,-1);
if (sca1==null) {
sca1 = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr1,
spinnerColumns,
new int[]{android.R.id.text1, android.R.id.text2},0
);
sp1.setAdapter(sca1);
} else {
sca1.swapCursor(csr1);
}
}
void setOrRefreshSpinner2() {
csr2 = dbHelper.getSpinnerData(sp2_table_name,-1);
if (sca2==null) {
sca2 = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
csr2,
spinnerColumns,
new int[]{android.R.id.text1, android.R.id.text2},0
);
sp2.setAdapter(sca2);
} else {
sca2.swapCursor(csr2);
}
}
private void addSomeData() {
long n1 = dbHelper.insertTable1Row("NAME001","The first name.");
long n2 = dbHelper.insertTable1Row("NAME002","The second name.");
long n3 = dbHelper.insertTable1Row("NAME003","The third name");
long t2n1 = dbHelper.insertTable2Row("CHILDNAME001",n1);
long t2n2 = dbHelper.insertTable2Row("CHILDNAME002",n2);
long t2n3 = dbHelper.insertTable2Row("CHILDNAME003", n3);
dbHelper.insertTable3Row("GRANDCHILDNAME001",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME002",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME003",t2n1);
dbHelper.insertTable3Row("GRANDCHILDNAME004",t2n2);
dbHelper.insertTable3Row("GRANDCHILDNAME005",t2n3);
}
}
Result
The above when run starts of with :-
With the first spinner dropdown shown :-
With the second spinner dropdown shown :-
If Button1 is clicked then both spinners (i.e. spinner2 has been changed to select data from Table1 rather than Table2) show data from Table1 (useless but for demonstration) :-
If Button3 is clicked then data from Table3 is displayed in the second spinner:-
Clicking Button2 shows data from Table2.
Of course the principle could be applied in many different ways.
My adapters were not set so I made below changes and got expected result.
// RETRIEVE
retrievebtn.setOnClickListener(arg0 -> {
// TODO Auto-generated method stub
nos.clear();
names.clear();
//OPEN
db.openDB();
//RETRIEVE
Cursor c = db.getAllValues();
c.moveToFirst();
while(!c.isAfterLast())
{
String no = c.getString(0);
nos.add(no);
String name = c.getString(1);
names.add(name);
c.moveToNext();
}
//CLOSE
c.close();
db.close();
//SET IT TO SPINNER
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, nos);
ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, names);
sp1.setAdapter(adapter1);
sp2.setAdapter(adapter2);
});
public class Main2Activity extends AppCompatActivity {
private EditText editText1, editText2, editText3, editText4;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
editText3 = (EditText) findViewById(R.id.editText3);
editText4 = (EditText) findViewById(R.id.editText4);
button = (Button) findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String un, pw, cpw, ph;
un = editText1.getText().toString();
pw = editText2.getText().toString();
cpw = editText3.getText().toString();
ph = editText4.getText().toString();
DbHelper dbHelpero = new DbHelper(Main2Activity.this);
SQLiteDatabase db = dbHelpero.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Entry.C_UNAME, un);
values.put(Entry.C_PASS, pw);
values.put(Entry.C_CPASS, cpw);
values.put(Entry.C_PNO, ph);
long newRowId = db.insert(Entry.TABLE_NAME, null, values);
if (newRowId == -1) {
Toast.makeText(getApplicationContext(), "Error while adding", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Yo Registration is complete", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Here is the Contract.java
public class Contract {
private Contract() {
}
public static final class Entry implements BaseColumns {
public final static String TABLE_NAME = "details";
public final static String _ID = BaseColumns._ID;
public final static String C_UNAME = "uname";
public final static String C_PASS = "pw";
public final static String C_CPASS = "cpw";
public final static String C_PNO = "pno";
}
}
And the DbHelper.java
public class DbHelper extends SQLiteOpenHelper {
public static final String LOG_TAG = DbHelper.class.getSimpleName();
public final static String DATABASE_NAME = "contacts.db";
private static final int DATABASE_VERSION = 1;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " ("
+ Entry._ID + " TEXT PRIMARY KEY AUTOINCREMENT, "
+ Entry.C_UNAME + " TEXT, "
+ Entry.C_PASS + " TEXT, "
+ Entry.C_CPASS + " TEXT, "
+ Entry.C_PNO + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
There are no syntax errors but still, the app is crashing.
Replace your CREATE_TABLE query with:
String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " ("
+ Entry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ Entry.C_UNAME + " TEXT, "
+ Entry.C_PASS + " TEXT, "
+ Entry.C_CPASS + " TEXT, "
+ Entry.C_PNO + " TEXT" + ")";
You can't have a TEXT type have an AUTOINCREMENT property as you currently have it on your _ID field. You need to change it to be an INTEGER so it can be used as PRIMARY KEY and then have it AUTOINCREMENT
Good day, I was trying to retrieved my data's and display them in a simple way.
Here's my sample code: SQLiteLocalDatabase .java
public class SQLiteLocalDatabase extends SQLiteOpenHelper{
private SQLiteDatabase sqLiteDatabase;
private static final String DB_NAME = "project.db";
private static final int VERSION = 1;
public static final String DB_TABLE = " user ";
public static final String ID = " _id ";
public static final String FULL_NAME = " fullname ";
public static final String LOCATION = " location ";
public static final String EMAIL_ADD = " email ";
public static final String PASSWORD = " password ";
public SQLiteLocalDatabase(Context context) {
super(context, DB_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String queryTable = " CREATE TABLE " + DB_TABLE + "( " + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+ FULL_NAME + " TEXT , " + LOCATION + " TEXT NOT NULL, " + EMAIL_ADD + " TEXT , " + PASSWORD + " TEXT " + " ) ";
//setUpDb();
db.execSQL(queryTable);
}
public void setUpDb(){
//TO OPEN DATABASE - RE-WRITABLE
sqLiteDatabase = getWritableDatabase();
}
public void closeTransactionDb(){
//CLOSE DB IF OPEN
if(sqLiteDatabase != null && sqLiteDatabase.isOpen()){
sqLiteDatabase.close();
}
}
//INSERT DATA
public long insert(int id,String fullname, String location,String email,String password){
//CONTENT VALUE contains name-value-pairs
ContentValues values = new ContentValues();
if(id != -1) {
values.put(ID,id);
values.put(FULL_NAME, fullname);
values.put(LOCATION, location);
values.put(EMAIL_ADD, email);
values.put(PASSWORD, password);
}
//Object Table, column, values
return sqLiteDatabase.insert(DB_TABLE, null, values);
}
//UPDATE
public long update(int id, String fullname,String location,String email, String password){
//CONTENT VALUE contains name-value-pairs
ContentValues values = new ContentValues();
values.put(FULL_NAME,fullname);
values.put(LOCATION,location);
values.put(EMAIL_ADD,email);
values.put(PASSWORD,password);
//WHERE
String where = ID + " = " +id;
//Object Table, values, destination-id
return sqLiteDatabase.update(DB_TABLE, values, where, null);
}
//DELETE
//
public long delete(int id){
//WHERE
String where = ID + " = " +id;
//Object Table, values, destination-id
return sqLiteDatabase.delete(DB_TABLE, where, null);
}
public Cursor getAllRecords(){
String queryDB = "SELECT * FROM " + DB_TABLE;
return sqLiteDatabase.rawQuery(queryDB, null);
}
public Cursor getSingleRecord(){
String querySingleRecord = "SELECT * FROM " + DB_TABLE + "WHERE _id = " +ID;
return sqLiteDatabase.rawQuery(querySingleRecord,null);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
For my main: AddItemsActivity .java
public class AddItemsActivity extends AppCompatActivity implements View.OnClickListener{
SQLiteLocalDatabase sqLiteLocalDatabase;
TextView textViewDbData;
EditText editTextFullName;
EditText editTextAddress;
EditText editTextEmailAdd;
EditText editTextPassword;
EditText editTextIDNO;
Button btnSave;
Button btnUpdate;
Button btnSearch;
Button btnDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_items);
sqLiteLocalDatabase = new SQLiteLocalDatabase(AddItemsActivity.this);
//CALL FUNCTION
setUpWidgets();
}
public void setUpWidgets(){
textViewDbData = (TextView) findViewById(R.id.textViewDbData);
editTextFullName = (EditText) findViewById(R.id.editTextViewAddFullName);
editTextAddress = (EditText) findViewById(R.id.editTextAddLocation);
editTextEmailAdd = (EditText) findViewById(R.id.editTextAddEmailAddress);
editTextPassword = (EditText) findViewById(R.id.editTextRegPassword);
editTextIDNO = (EditText) findViewById(R.id.editTextAddID);
btnSave = (Button) findViewById(R.id.buttonAddContacts);
btnSave.setOnClickListener(this);
btnUpdate = (Button) findViewById(R.id.buttonUpdate);
btnUpdate.setOnClickListener(this);
btnSearch = (Button) findViewById(R.id.buttonDeleteRecord);
btnSearch.setOnClickListener(this);
btnDelete = (Button) findViewById(R.id.buttonShowRecords);
btnDelete.setOnClickListener(this);
}
public void clearTextFields(){
editTextFullName.setText("");
editTextAddress.setText("");
editTextEmailAdd.setText("");
editTextPassword.setText("");
editTextIDNO.setText("");
}
#Override
public void onClick(View v) {
String fullName = editTextFullName.getText().toString().trim();
String location = editTextAddress.getText().toString().trim();
String emailAdd = editTextEmailAdd.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
switch (v.getId()){
case R.id.buttonAddContacts:
//IF result == -1
long result = sqLiteLocalDatabase.insert(Integer.parseInt(getValue(editTextIDNO)), fullName, location, emailAdd, password);
if(result == -1){
Toast.makeText(AddItemsActivity.this, "Error: Someone own that Id",Toast.LENGTH_LONG).show();
}else
{
Toast.makeText(AddItemsActivity.this, "Success Id: " +result,Toast.LENGTH_LONG).show();
clearTextFields();
}
break;
case R.id.buttonUpdate:
if(editTextIDNO.getText().equals("")){
Toast.makeText(AddItemsActivity.this, "Please Enter User ID ",Toast.LENGTH_LONG).show();
}
else {
long update = sqLiteLocalDatabase.update(Integer.parseInt(getValue(editTextIDNO)),
getValue(editTextFullName),
getValue(editTextAddress),
getValue(editTextEmailAdd),
getValue(editTextPassword)
);
if (update == 0) {
Toast.makeText(AddItemsActivity.this, "Error Updating ", Toast.LENGTH_LONG).show();
} else if (update == -1) {
Toast.makeText(AddItemsActivity.this, "Successfully Modified", Toast.LENGTH_LONG).show();
clearTextFields();
} else {
Toast.makeText(AddItemsActivity.this, "Error All data updated Id: " + update, Toast.LENGTH_LONG).show();
}
}
break;
case R.id.buttonDeleteRecord:
long delete = sqLiteLocalDatabase.delete(Integer.parseInt(getValue(editTextIDNO)));
if(delete == 0) {
Toast.makeText(AddItemsActivity.this, "Error Delete", Toast.LENGTH_LONG).show();
} else
{
Toast.makeText(AddItemsActivity.this, "Success Delete", Toast.LENGTH_LONG).show();
clearTextFields();
}
break;
case R.id.buttonShowRecords:
StringBuffer finalData = new StringBuffer();
Cursor cursor = sqLiteLocalDatabase.getAllRecords();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext() ){
finalData.append(cursor.getLong(cursor.getColumnIndex(sqLiteLocalDatabase.ID)));
finalData.append(" - ");
finalData.append(cursor.getString(cursor.getColumnIndex(sqLiteLocalDatabase.FULL_NAME)));
finalData.append(" - ");
finalData.append(cursor.getString(cursor.getColumnIndex(sqLiteLocalDatabase.LOCATION)));
finalData.append(" - ");
finalData.append(cursor.getInt(cursor.getColumnIndex(sqLiteLocalDatabase.EMAIL_ADD)));
finalData.append(" - ");
finalData.append(cursor.getInt(cursor.getColumnIndex(sqLiteLocalDatabase.PASSWORD)));
finalData.append("\n");
}
textViewDbData.setText(finalData);
break;
}
}
public String getValue(EditText editText){
return editText.getText().toString().trim();
}
#Override
protected void onStart() {
super.onStart();
sqLiteLocalDatabase.setUpDb();
}
#Override
protected void onStop() {
super.onStop();
sqLiteLocalDatabase.closeTransactionDb();
}
My problem was with the getAllRecords in the append part.
Logcat:
This is because one of the method of getting column index like cursor.getColumnIndex(sqLiteLocalDatabase.ID) returns -1.
Make sure the Cursor contains all the columns you are retrieving and check if getColumnIndex method is not returning -1.
if(cursor.getColumnIndex(sqLiteLocalDatabase.ID) != -1) {
finalData.append(cursor.getLong(cursor.getColumnIndex(sqLiteLocalDatabase.ID)));
finalData.append(" - ");
}
Likewise check all conditions.
Hope it'll work.
Im trying to update a users current credits, but I don't want to replace the value, just add on a selected amount from the spinner and add it on to the the users current credits? Thank you.
My database code?
package com.example.parkangel;
public class UDbHelper extends SQLiteOpenHelper
{
public static final String KEY_ROWID = "_id";
public static final String KEY_PFNAME = "payeeFname";
public static final String KEY_PSNAME = "payeeSname";
public static final String KEY_CARD = "card";
public static final String KEY_CREDITS = "credits";
private static final String DATABASE_NAME = "UserData.db";
private static final String DATABASE_TABLE = "UserTable";
private static final int DATABASE_VERSION = 1;
//private UDbHelper dbHelper;
//private final Context ourContext;
private static UDbHelper instance;
private SQLiteDatabase ourDatabase;
public UDbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static UDbHelper getInstance(Context context)
{
if (instance == null)
{
instance = new UDbHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_PFNAME + " TEXT NOT NULL, " + KEY_PSNAME + "
TEXT NOT NULL, " +
KEY_CARD + " INTEGER NOT NULL, " + KEY_CREDITS + "
INTEGER NOT NULL);");
ContentValues values = new ContentValues();
values.put(KEY_PFNAME, "Tutku");
values.put(KEY_PSNAME, "Erbil");
values.put(KEY_CARD, "12345677");
values.put(KEY_CREDITS, 5);
db.insert(DATABASE_TABLE, null, values);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public synchronized UDbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen())
ourDatabase = getWritableDatabase();
return this;
}
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[] {KEY_ROWID, KEY_PFNAME, KEY_PSNAME,
KEY_CARD, KEY_CREDITS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
String result = " ";
int iRow = c.getColumnIndexOrThrow(KEY_ROWID);
int iPFname = c.getColumnIndexOrThrow(KEY_PFNAME);
int iPSname = c.getColumnIndexOrThrow(KEY_PSNAME);
int iCard = c.getColumnIndexOrThrow(KEY_CARD);
int iCredits = c.getColumnIndexOrThrow(KEY_CREDITS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname) + " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n";
}
return result;
}
public void upDateUser(String money) {
// TODO Auto-generated method stub
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_CREDITS, money);
ourDatabase.update(DATABASE_TABLE, cvUpdate, null, null);
}
}
Class that needs to perform the actoin:
package com.example.parkangel;
public class Balance extends Activity implements OnClickListener{
Button add;
TextView display;
Spinner spinner3;
Integer[] money = new Integer[] {1, 2, 5, 10};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.balance_layout);
TextView tv = (TextView) findViewById(R.id.firstn);
UDbHelper db = new UDbHelper(this);
db.open();
String data = db.getData();
//db.addUser();
db.close();
tv.setText(data);
ArrayAdapter<Integer> adapter3 = new ArrayAdapter<Integer>(Balance.this,
android.R.layout.simple_spinner_item, money);
spinner3 = (Spinner) findViewById (R.id.moneytoadd);
spinner3.setAdapter(adapter3);
add = (Button) findViewById(R.id.topup);
add.setOnClickListener(this);
//add = (Button) findViewById(R.id.topup);
}
public void onClick(View arg0)
{
switch (arg0.getId()){
case R.id.topup:
boolean work = true;
try{
String money = spinner3.getContext().toString();
UDbHelper ud = new UDbHelper(this);
ud.open();
ud.upDateUser(money);
ud.close();
}catch (Exception e){
work = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Unable To TopUp!");
TextView dg = new TextView(this);
dg.setText(error);
d.setContentView(dg);
d.show();
}finally{
if(work){
Dialog d = new Dialog(this);
d.setTitle("You Have ToppedUp!");
TextView dg = new TextView(this);
dg.setText("TopUp Successful");
d.setContentView(dg);
d.show();
}
}
break;
}
}
public void updateActivity(View view){
Intent book = new Intent(Balance.this, BookTicket.class);
startActivity(book);
}
public void addBalance(View view){
Intent addB = new Intent(Balance.this, Balance.class);
startActivity(addB);
}
public void doUpdate(View view){
Intent upd = new Intent(Balance.this, UpdateTicket.class);
startActivity(upd);
}
}
First of all you should have an ID that will let you find the user you are interested in. That do a select to get the current value that is stored in database. Parse the value to integer and add "new" money. And finally, update the value in database.
public void upDateUser(String ID, String money) {
String query = "Select money from TABLE_NAME where ID = " + ID;
SQLiteDatabase db = this.getWriteableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
int oldMoney = 0;
if (cursor.moveToFirst()) {
oldMoney = Integer.parseInt(cursor.getString(0)); //Cause we get only from money column
}
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_CREDITS, oldMoney + money);
String filter = "UID" + "=" + ID;
db.update(DATABASE_TABLE, cvUpdate, filter, null);
}
Of course you have to check if cursor returns exactly one row and do some other checks.
I've been trying to populate an Android Listview from a SQLite database using the code below. I have successfully done this from an array inside the same class. But in this case I'm attempting to populate it from a String array I have returned from another class. I'm new to this so am possibly doing this completely wrong. If anyone could look at the code and advise to what I'm doing wrong that'd be brilliant.
Any help would be really appreciated with this as I'm under serious pressure to get it finished, Thanks!
LoginActivity Class
public class LoginActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final EditText txtUserName = (EditText)findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText)findViewById(R.id.txtPassword);
Button btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
try{
if(username.length() > 0 && password.length() >0)
{
DBUserAdapter dbUser = new DBUserAdapter(LoginActivity.this);
dbUser.open();
int UID = dbUser.Login(username, password);
if(UID != -1)
{
// TEST
//int UID = dbUser.getUserID(username, password);
//getSitesByClientname(UID);
// END TEST
// MY TEST CODE TO CHANGE ACTIVITY TO CLIENT SITES
Intent myIntent = new Intent(LoginActivity.this, ClientSites.class);
//Intent myIntent = new Intent(getApplicationContext(), ClientSites.class);
myIntent.putExtra("userID", UID);
startActivity(myIntent);
//finish();
// END MY TEST CODE
//Cursor UserID = dbUser.getUserID();
Toast.makeText(LoginActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(LoginActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
dbUser.close();
}
}catch(Exception e)
{
Toast.makeText(LoginActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
Method from DBHelper Class to return String Array
public String[] getSitesByClientname(String id) {
String[] args={id};
//return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
// loop through all rows and adding to array
int count;
count = myCursor.getCount();
final String[] results = new String[count];
results[0] = new String();
int i = 0;
try{
if (myCursor.moveToFirst()) {
do {
results[i] = myCursor.getString(myCursor.getColumnIndex("client_sitename"));
} while (myCursor.moveToNext());
}
}finally{
myCursor.close();
}
db.close();
// return results array
return results;
ClientSites Class
public class ClientSites extends ListActivity {
public final static String ID_EXTRA="com.example.loginfromlocal._ID";
private DBUserAdapter dbHelper = null;
//private Cursor ourCursor = null;
private ArrayAdapter<String> adapter=null;
//#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
//int uID = i.getIntExtra("userID", 0);
//ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
dbHelper.createDatabase();
//dbHelper.openDataBase();
dbHelper.open();
String[] results = dbHelper.getSitesByClientname(uID);
//setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
//adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));
//ListView myListView = (ListView)findViewById(R.id.myListView);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
//CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
//adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
//myListView.setAdapter(adapter);
//myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
}
Any help with this would be great, Thanks!
Create own project with few activities. Start working with sqlite database
Create new application. Create login activity and DB helper. Trying to upload dada from DB. Reseach and development
Here is an example how to work with SQLite DB.
public class DBHelper extends SQLiteOpenHelper {
private static DBHelper instance;
private static final String DATABASE_NAME = "UserClientBase";
private static final int DATABASE_VERSION = 1;
public static interface USER extends BaseColumns {
String TABLE_NAME = "userTable";
String NAME = "userName";
String PASSWORD = "userPassword";
}
public static interface CLIENT extends BaseColumns {
String TABLE_NAME = "clientTable";
String NAME = "clientName";
String USER_ID = "userId";
}
private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS ";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS ";
private static final String UNIQUE = "UNIQUE ON CONFLICT ABORT";
private static final String CREATE_TABLE_USER = CREATE_TABLE + USER.TABLE_NAME + " (" + USER._ID
+ " INTEGER PRIMARY KEY, " + USER.NAME + " TEXT " + UNIQUE + ", " + USER.PASSWORD + " TEXT);";
private static final String CREATE_TABLE_CLIENT = CREATE_TABLE + CLIENT.TABLE_NAME + " (" + CLIENT._ID
+ " INTEGER PRIMARY KEY, " + CLIENT.NAME + " TEXT UNIQUE, " + CLIENT.USER_ID + " INTEGER);";
private DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DBHelper getInstance(Context context) {
if (instance == null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USER);
db.execSQL(CREATE_TABLE_CLIENT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE + USER.TABLE_NAME);
db.execSQL(DROP_TABLE + CLIENT.TABLE_NAME);
onCreate(db);
}
public long createUser(String newUserName, String newUserPassword) {
ContentValues values = new ContentValues();
values.put(USER.NAME, newUserName);
values.put(USER.PASSWORD, newUserPassword);
return getWritableDatabase().insert(USER.TABLE_NAME, null, values);
}
public long createClient(long userId, String newClientName) {
ContentValues values = new ContentValues();
values.put(CLIENT.USER_ID, userId);
values.put(CLIENT.NAME, newClientName);
return getWritableDatabase().insert(CLIENT.TABLE_NAME, null, values);
}
public boolean isCorrectLoginPassword(String login, String password) {
Cursor userListCursor = getReadableDatabase().rawQuery(
"SELECT * FROM " + USER.TABLE_NAME + " WHERE " + USER.NAME + " =? AND " + USER.PASSWORD
+ " =?", new String[] { login, password });
if ((userListCursor != null) && (userListCursor.getCount() > 0)) {
return true;
} else {
return false;
}
}
public Cursor getUserClientList(String userName) {
Cursor userClientList = getReadableDatabase().rawQuery(
"SELECT * FROM " + CLIENT.TABLE_NAME + " INNER JOIN " + USER.TABLE_NAME
+ " ON " + CLIENT.USER_ID + " = " + USER.TABLE_NAME + "." + USER._ID + " WHERE "
+ USER.NAME + " =?", new String[] { userName });
return userClientList;
}
}
Example of login button click listener.
String login = loginEdt.getText().toString();
String password = passwordEdt.getText().toString();
boolean loginSuccess = databaseHelper.isCorrectLoginPassword(login, password);
if(loginSuccess) {
Intent clientListIntent = new Intent(LoginActivity.this, ClientListActivity.class);
clientListIntent.putExtra(ClientListActivity.EXTRAS_LOGIN, login);
startActivity(clientListIntent);
} else {
Toast.makeText(LoginActivity.this, "Incorrect login/password", Toast.LENGTH_SHORT).show();
}
And example of listview with data from sql:
clientLv= (ListView)findViewById(R.id.listClient);
login = getIntent().getExtras().getString(EXTRAS_LOGIN);
dbHelper = DBHelper.getInstance(this);
Cursor clientList = dbHelper.getUserClientList(login);
adapter = new SimpleCursorAdapter(this, R.layout.row_client, clientList, new String[]{DBHelper.CLIENT.NAME}, new int[]{R.id.txtClientName} , SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
clientLv.setAdapter(adapter);