Can't add more than one record, ID not autoincrimenting - java

I'm trying to add site details to a database and then after I insert a row, output the result to a TextView. The record is being inserted into the database because it's being shown in a TextView, however I can only insert one record and I'm not sure why. I'm been using the tutorial here and modifying it to meet my needs.
Here is my DBAdapter:
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String address, String username,
String password, int port) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, username);
initialValues.put(KEY_PASSWORD, password);
initialValues.put(KEY_PORT, port);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String address,
String username, String password, String port) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
// newValues.put(KEY_PASSWORD, password);
// newValues.put(KEY_PORT, port);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
I'm querying the database here:
public class FTPConnector extends Activity {
DBAdapter myDb;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.ftp);
status = (TextView) findViewById(R.id.status);
editAddress = (EditText) findViewById(R.id.editAddress);
editUser = (EditText) findViewById(R.id.editUsername);
editPassword = (EditText) findViewById(R.id.editPassword);
addsiteBtn = (Button) findViewById(R.id.addsiteBtn);
addsiteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
siteManager();
}
});
openDb();
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
//Where the insertRecord() happens
public void siteManager() {
final AlertDialog customDialog = new AlertDialog.Builder(this).create();
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.site_manager, null);
final EditText tmpname = (EditText) view
.findViewById(R.id.dialogsitename);
final EditText tmpaddress = (EditText) view
.findViewById(R.id.dialogaddress);
final EditText tmpuser = (EditText) view
.findViewById(R.id.dialogusername);
final EditText tmppass = (EditText) view
.findViewById(R.id.dialogpassword);
final EditText tmpport = (EditText) view.findViewById(R.id.dialogport);
final TextView tmpsites = (TextView) view.findViewById(R.id.textView6);
final CheckBox tmppassive = (CheckBox) view
.findViewById(R.id.dialogpassive);
final Button tmpclose = (Button) view.findViewById(R.id.closeBtn);
final Button tmptestBtn = (Button) view.findViewById(R.id.testBtn);
final Button tmpsavetsite = (Button) view.findViewById(R.id.saveSite);
customDialog.setView(tmpclose);
customDialog.setView(tmptestBtn);
customDialog.setView(tmpname);
customDialog.setView(tmpaddress);
customDialog.setView(tmpuser);
customDialog.setView(tmppass);
customDialog.setView(tmpport);
customDialog.setView(tmppassive);
customDialog.setView(tmpsavetsite);
customDialog.setView(tmpsites);
tmpclose.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
tmptestBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = tmpname.getText().toString();
_address = tmpaddress.getText().toString();
_user = tmpuser.getText().toString();
_pass = tmppass.getText().toString();
_port = Integer.parseInt(tmpport.getText().toString());
_passive = false;
if (tmppassive.isChecked()) {
_passive = true;
}
boolean status = ftpConnect(_address, _user, _pass, _port);
if (status == true) {
Toast.makeText(FTPConnector.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(FTPConnector.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
tmpsavetsite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tmpsites.setText("");
String msg = "!";
_name = tmpname.getText().toString();
_address = tmpaddress.getText().toString();
_user = tmpuser.getText().toString();
_pass = tmppass.getText().toString();
_port = Integer.parseInt(tmpport.getText().toString());
long newId = myDb.insertRow(_name, _address, _user, _pass, 21);
Cursor c = myDb.getAllRows();
if (c.moveToFirst()) {
int id = c.getInt(0);
String _name = c.getString(1);
String _address = c.getString(2);
String _user = c.getString(3);
String _pass = c.getString(4);
int _port = c.getInt(5);
msg += "id=" + id + "\n";
msg += ", name=" + _name + "\n";
msg += ", address=" + _address + "\n";
msg += ", username=" + _user + "\n";
msg += ", password=" + _pass + "\n";
msg += ", port=" + _port + "\n";
while (c.moveToNext());
}
c.close();
// displayText(msg);
tmpsites.setText(msg);
}
});
customDialog.setView(view);
customDialog.show();
}
Why can't I add more than one record?

In here :
while (c.moveToNext()); //<<<
currently you are not using any loop like do-while for iterating through cursor(you forget to add do block with while). get all data from cursor as using for loop:
//more to the first row
c.moveToFirst();
//iterate over rows
for (int i = 0; i < c.getCount(); i++) {
// get all data here from current row..
//move to the next row
c.moveToNext();
}
//close the cursor
c.close();
and using do-while you can get all values from current row as:
c.moveToFirst(); //more to the first row
do {
// get all data here from current row..
} while (c.moveToNext());

Related

how to add another column in another spinner of same or other table in android studio

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);
});

Get value from cursor everytime when database is updated

I've got two activities. One is updating value in database from edittext and in the second activity i want put this value from database into textview. At the first time when i update value everything goes well but at the second time textview cant be updated and i see in the Textview value "0". When i gave breakpoints i see that my cursor didnt want to take value second time. Any suggestion what should i do ? It's problem with lifecycle of activity or what? There is my code. Any example or suggestion will be very helpful for me.
public class DzienPierwszy extends AppCompatActivity {
Button button;
OpenHelper1 mDb;
TextView pp1,pp2,pp3,s1,s2,s3,p1,p2,p3,pn,sr,pt,nd;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.dzien_treningu);
p1 = (TextView) findViewById(R.id.p1);
p2 = (TextView) findViewById(R.id.p2);
p3 = (TextView) findViewById(R.id.p3);
s1 = (TextView) findViewById(R.id.s1);
s2 = (TextView) findViewById(R.id.s2);
s3 = (TextView) findViewById(R.id.s3);
pp1 = (TextView) findViewById(R.id.pp1);
pp2 = (TextView) findViewById(R.id.pp2);
pp3 = (TextView) findViewById(R.id.pp3);
pn = (TextView) findViewById(R.id.pn);
sr = (TextView) findViewById(R.id.sr);
pt = (TextView) findViewById(R.id.pt);
nd = (TextView) findViewById(R.id.nd);
Intent i = getIntent();
final String product = i.getStringExtra("cwiczenie ");
int lol1=0;
mDb = new OpenHelper1(this);
mDb.open();
// fetch data about 1 row in database table
Cursor test = mDb.fetchOneCwiczenie(product);
mDb.close();
if( test != null && test.moveToFirst() ){
//get value from column
lol1 = test.getInt(test.getColumnIndex("score"));
test.close();
}
p1.setText(String.valueOf(Math.round(lol1*0.55)));
p2.setText(String.valueOf(Math.round(lol1*0.79)));
p3.setText(String.valueOf(Math.round(lol1*0.67)));
s1.setText(String.valueOf(Math.round(lol1*0.67)));
s2.setText(String.valueOf(Math.round(lol1*0.91)));
s3.setText(String.valueOf(Math.round(lol1*0.79)));
pp1.setText(String.valueOf(Math.round(lol1*0.79)));
pp2.setText(String.valueOf(Math.round(lol1*1.03)));
pp3.setText(String.valueOf(Math.round(lol1*0.91)));
}
public void open(View view) {
Intent intent = new Intent(getApplicationContext(),TestActivity.class);
startActivity(intent);
}
}
public class OpenHelper1{
private static final String TAG = "TreningDbAdapter";
public DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private final ContentResolver resolver =null;
private final Context mCtx;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "menadzerCwiczen1";
public static final String TABLE_CWICZENIA = "cwiczenia";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_KIND = "kind";
public static final String KEY_URL = "url";
public static final String KEY_SCORE = "score";
public static final String KEY_SERIES = "series";
static final String PROVIDER_NAME = "com.example.jacek.gympartner.SQLite";
static final String URL = "content://" + PROVIDER_NAME + "/cwiczenia";
static final Uri CONTENT_URI = Uri.parse(URL);
private static HashMap<String, String> CWICZENIA_PROJECTION_MAP;
static final int CWICZENIA = 1;
static final int CWICZENIE_ID = 2;
static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "cwiczenie", CWICZENIA);
uriMatcher.addURI(PROVIDER_NAME, "cwiczenia/#", CWICZENIE_ID);
}
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + TABLE_CWICZENIA + " (" +
KEY_ID + " integer PRIMARY KEY autoincrement," +
KEY_NAME + " TEXT," +
KEY_KIND + " TEXT," +
KEY_URL + " TEXT," +
KEY_SCORE + " TEXT," +
KEY_SERIES + " integer" +
");";
/*
#Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
mDb = dbHelper.getWritableDatabase();
return (mDb == null)? false:true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return null;
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Pompki','Klatka piersiowa','https://www.youtube.com/watch?v=bwnidT3CB_Q',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Pompki na poręczach','Triceps','https://www.youtube.com/watch?v=Cufsu3IHhCo',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Odwrotne wiosłowanie','Plecy','https://www.youtube.com/watch?v=8qCn76yKhro',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Spięcia brzucha leżąc','Górna część mięśni brzucha','https://www.youtube.com/watch?v=VVcm4LdmIwM',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Unoszenie kolan','Dolna część mięśni brzucha','https://www.youtube.com/watch?v=Htx9Z8ZkiCg',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Skręty tułowia','Mięśnie skośne brzucha','https://www.youtube.com/watch?v=i7smKA3mgBU',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Przysiady','Uda','https://www.youtube.com/watch?v=NEduXlZ8zSk&t',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Wspięcia na palce','Mięśnie łydek','https://www.youtube.com/watch?v=Wri0VppFWCY',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Podciąganie na drążku','Mięśnie łydek','https://www.youtube.com/watch?v=7hM1iriAxx8',0,3)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CWICZENIA);
onCreate(db);
}
}
public OpenHelper1(Context ctx) {
this.mCtx = ctx;
}
public OpenHelper1 open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public OpenHelper1 read() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getReadableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCwiczenie(String name,
String kind,
String url,
int score,
int series) {
mDbHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_KIND, kind);
initialValues.put(KEY_URL, url);
initialValues.put(KEY_SCORE, score);
initialValues.put(KEY_SERIES, series);
return mDb.insert(TABLE_CWICZENIA, null, initialValues);
}
public void deleteCwiczenie(String name) {
mDb.execSQL("DELETE FROM " + TABLE_CWICZENIA + " WHERE " + KEY_NAME + "=\"" + name + "\";" );
}
public void updateScore1(Uri uri,String name, int wynik) {
String str = "UPDATE "+TABLE_CWICZENIA+" SET "+KEY_SCORE+" = "+wynik+" WHERE "+KEY_NAME+" = '"+name+"'";
mDb.execSQL(str);
}
public void updateScore(String name, int wynik) {
String str = "UPDATE "+TABLE_CWICZENIA+" SET "+KEY_SCORE+" = "+wynik+" WHERE "+KEY_NAME+" = '"+name+"'";
mDb.execSQL(str);
}
public boolean deleteAllCwiczenia() {
int doneDelete = 0;
doneDelete = mDb.delete(TABLE_CWICZENIA, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public Cursor fetchCwiczeniaByName(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(TABLE_CWICZENIA, new String[] {KEY_ID,
KEY_NAME, KEY_KIND, KEY_URL, KEY_SCORE, KEY_SERIES},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, TABLE_CWICZENIA, new String[] {KEY_ID,
KEY_NAME, KEY_KIND, KEY_URL, KEY_SCORE, KEY_SERIES},
KEY_NAME + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllcwiczenia() {
Cursor mCursor = mDb.query(TABLE_CWICZENIA, new String[] {KEY_ID,
KEY_NAME, KEY_KIND, KEY_URL, KEY_SCORE, KEY_SERIES},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchOneCwiczenie(String name) {
String query = "SELECT * FROM " + TABLE_CWICZENIA + " WHERE name='"+name+"'";
Cursor c = mDb.rawQuery(query,null);
if(c != null) {
c.moveToFirst();
}
return c;
}
public Cursor fetchOneCwiczenie1(Uri uri,String name) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_CWICZENIA);
String query = "SELECT * FROM " + TABLE_CWICZENIA + " WHERE name='"+name+"'";
Cursor c = mDb.rawQuery(query,null);
if (c != null) {
// c.setNotificationUri(getContext().getContentResolver(), ContactsContract.AUTHORITY_URI);
}
return c;
}
public void insertSomeCwiczenia() {
createCwiczenie("Pompki","Klatka piersiowa","https://www.youtube.com/watch?v=bwnidT3CB_Q",20,3);
createCwiczenie("Pompki na poręczach","Triceps","https://www.youtube.com/watch?v=Cufsu3IHhCo",0,3);
createCwiczenie("Odwrotne wiosłowanie","Plecy","https://www.youtube.com/watch?v=8qCn76yKhro",0,3);
createCwiczenie("Spięcia brzucha leżąc","Górna część mięśni brzucha","https://www.youtube.com/watch?v=VVcm4LdmIwM",0,3);
createCwiczenie("Unoszenie kolan","Dolna część mięśni brzucha","https://www.youtube.com/watch?v=Htx9Z8ZkiCg",0,3);
createCwiczenie("Skręty tułowia","Mięśnie skośne brzucha","https://www.youtube.com/watch?v=i7smKA3mgBU",0,3);
createCwiczenie("Przysiady","Uda","https://www.youtube.com/watch?v=NEduXlZ8zSk&t",0,3);
createCwiczenie("Wspięcia na palce","Mięśnie łydek","https://www.youtube.com/watch?v=Wri0VppFWCY",0,3);
createCwiczenie("Podciąganie na drążku","Mięśnie łydek","https://www.youtube.com/watch?v=7hM1iriAxx8",0,3);
}
}
public class TestActivity extends AppCompatActivity {
TextView textView;
EditText editText;
Button button,button1;
OpenHelper1 mDb;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.test_layout);
textView = (TextView) findViewById(R.id.polecenie);
editText = (EditText) findViewById(R.id.wartosc);
button = (Button) findViewById(R.id.treningactivity);
button1 = (Button) findViewById(R.id.zapisz);
//button2 = (Button) findViewById(R.id.button);
mDb = new OpenHelper1(this);
Intent i = getIntent();
// getting attached intent data
final String product = i.getStringExtra("cwiczenie ");
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int wynik = Integer.parseInt(editText.getText().toString());
mDb.open();
mDb.updateScore(product,wynik);
mDb.close();
}
});
/*
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDb.open();
Cursor t = mDb.fetchOneCwiczenie(product);
int c = t.getInt(t.getColumnIndex("score"));
String k = Integer.toString(c);
textView1.setText(k);
mDb.close();
}
});
*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext().getApplicationContext(), DzienPierwszy.class);
i.putExtra("cwiczenie ", product);
startActivity(i);
}
});
}
}
There are more than couple of things that you need to do -
In your content provider, you need to attach a notification Uri before the Cursor is being returned to client (in this case your Activity). The code would look something like this (Here the Authority URI need to be changed as per your provider) -
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(),ContactsContract.AUTHORITY_URI);
}
return c;
Every time there is a update in data, the following line needs to be called -
getContext().getContentResolver().notifyChange(ContactsContract.AUTHORITY_URI, null,
syncToNetwork);
Basically what point 1 & 2 does is that it notifies the underlying data layer that there is currently a client with an active cursor and needs to be notified if there is a change in the underlying data. If you are using any of the inbuilt data providers in Android like ContactsProvider/SmsProvider to read contacts/SMS data, point 1 &2 would have been taken care.
ContactsProvider
And on your activity code you need to do something like
cursor.registerContentObserver(mChangeObserver). If you instead use a Cursor adapter which wraps around your cursor, then this would have been taken care. Have a look at the Cursor Adapter source code -
CursorAdapter Sample

No data retrieved if open sqlite more than once

When I add data into sqlite and open it for the first time, the data inside will be displayed. However, if I try opening it again nothing will show up even though there is data inside. May I know what is the problem?
Class that performs the activity:
public class Watchlist extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DatabaseHandler.TABLE_ITEM;
private SQLiteDatabase newDB;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("This data is retrieved from sqlite");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
DatabaseHandler db = new DatabaseHandler(this.getApplicationContext());
newDB = db.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT * FROM " + tableName, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String pid = c.getString(c.getColumnIndex("id"));
String name = c.getString(c.getColumnIndex("name"));
String price = c.getString(c.getColumnIndex("price"));
String date = c.getString(c.getColumnIndex("created_at"));
Log.d("pid",pid);
results.add("Name: " + name + "\n Price: " + price + "\n Date posted: " + date);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
Database handler:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 2;
// Database Name
private static final String DATABASE_NAME = "itemManager";
// table name
public static final String TABLE_ITEM = "item";
// Item Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PRICE = "price";
private static final String KEY_CREATED_AT = "created_at";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_ITEM + "("
+ KEY_ID + " INTEGER PRIMARY KEY autoincrement,"
+ KEY_NAME + " TEXT, "
+ KEY_PRICE + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_ITEM_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEM);
// Create tables again
onCreate(db);
}
/**
* Storing item details in database
* */
public void addItem(Items item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.getName()); // item name
values.put(KEY_PRICE, item.getPrice()); // item price
values.put(KEY_CREATED_AT, item.getDate()); // Created At
// Inserting Row
db.insert(TABLE_ITEM, null, values);
db.close(); // Closing database connection
}
/**
* Getting item data from database
* */
public List<Items> getAllItems(){
List<Items> itemList = new ArrayList<Items>();
String selectQuery = "SELECT * FROM " + TABLE_ITEM;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
if (cursor.moveToFirst()) {
do {
Items item = new Items();
item.setID(Integer.parseInt(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDate(cursor.getString(2));
// Adding item to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
/**
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_ITEM;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
// Updating item
public int updateItem(Items item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.getName());
values.put(KEY_PRICE, item.getPrice());
values.put(KEY_CREATED_AT, item.getDate());
// updating row
return db.update(TABLE_ITEM, values, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
}
// Deleting item
public void deleteItem(Items item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEM, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
db.close();
}
}
Well, don't you delete all the records before closing the database?
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
That would explain that behaviour.

How to update a specific row in SQLite?

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.

Populate Android Listview from SQLite database

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);

Categories