why my first created row in database have id null1 - java

my problem is, when I put something in my text fields and save that to database, the ID of that row is null1
instead of 1
here is my code for creating database and putting data in database :
private HelperDb myHelper;
private final Context myContext;
private SQLiteDatabase myDatabase;
private static class HelperDb extends SQLiteOpenHelper {
public HelperDb(Context context) {
super(context, DATABASE_NAME, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " STRING, " +
KEY_TEKST + " TEXT, " +
KEY_DATUM + " STRING, " +
KEY_VREME + " STRING);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
this.onCreate(db);
}
}
public Baza(Context c){
myContext = c;
}
public Baza open() throws SQLException {
myHelper = new HelperDb(myContext);
myDatabase = myHelper.getWritableDatabase();
return this;
}
public void close() {
myHelper.close();
}
// this is how I put data in database
public long unesiPodatkeBaza(String ime, String napisaniTekst, String uneseniDatum, String unesenoVreme) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, ime);
cv.put(KEY_TEKST, napisaniTekst);
cv.put(KEY_DATUM, uneseniDatum);
cv.put(KEY_VREME, unesenoVreme);
return myDatabase.insert(DATABASE_TABLE, null, cv);
}
later that make problem for application.
This is how I collect data from database:
public String[] getData() {
String[] kolone = new String[]{KEY_ROWID, KEY_NAME, KEY_TEKST, KEY_DATUM, KEY_VREME};
Cursor c = myDatabase.query(DATABASE_TABLE, kolone, null, null, null, null, null);
iRed = c.getColumnIndex(KEY_ROWID);
iIme = c.getColumnIndex(KEY_NAME);
iTekst = c.getColumnIndex(KEY_TEKST);
iDatum = c.getColumnIndex(KEY_DATUM);
iVreme = c.getColumnIndex(KEY_VREME);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRed) + " " + c.getString(iIme) + " " + c.getString(iTekst) + " " + c.getString(iDatum) + " " + c.getString(iVreme) + "\n";
}
return result.split("\n");
}
and this is what I'm doing with data:
public class SQLPregled extends Activity{
public String[] data;
private ListView lv;
private int idSend;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.pregledbaze);
lv = (ListView) findViewById(R.id.lvListaBaza);
final Baza izlistavanje = new Baza(this);
izlistavanje.open();
data = izlistavanje.getData();
izlistavanje.close();
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data));
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String tmplv = lv.getItemAtPosition(position).toString();
String[] odvojeni = tmplv.split(" ");
idSend = Integer.parseInt(odvojeni[0]);
AlertDialog.Builder adb = new AlertDialog.Builder(SQLPregled.this);
adb.setTitle("Dali zelite da obrisete izabranu poruku?");
adb.setMessage("Id je : " + odvojeni[0]);
adb.setPositiveButton("Obrisi", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
izlistavanje.open();
izlistavanje.deleteData(idSend);
izlistavanje.close();
onCreate(null);
}
});
adb.setNegativeButton("Odustani", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
adb.show();
}
});
} // onCreate
}

it certainly can not have an ID of "null1" as the table definition has the ID defined as an INTEGER, so you would get errors when trying to set that value and the db would not store it that way.
it's more likely that when you're reading / displaying it, you're appending it to a null value so null + 1 = "null1" though some sort of string cast hocus pocus. Can you show us how you're getting and displaying the id field? Why do you think it's "null1"?

Related

How to sum my column value in SQLite?

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.

no columns in mysqlite database

I made an android eclipse project that uses SQLite as a database.
Some errors occur when I try to run the project on the phone. When I click the view button(to view my database), The application says:
no columns in my database.
Why does it happen?
Data Layer:
public class Translator {
public static final String KEY_ROWID ="_id";
public static final String KEY_DESC ="page_desc";
private static final String DATABASE_NAME ="Translatordb";
private static final String DATABASE_TABLE ="pageTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " STRING PRIMARY KEY, " +
KEY_DESC + " TEXT NOT NULL);"
);
}
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 Translator(Context c){
ourContext = c;
}
public Translator open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String id, String description){
ContentValues cv = new ContentValues();
cv.put(KEY_ROWID,id);
cv.put(KEY_DESC,description);
return ourDatabase.insert(DATABASE_TABLE,null, cv);
}
public long createEntry1(String id, String description){
ContentValues cv = new ContentValues();
cv.put(KEY_ROWID,"P01");
cv.put(KEY_DESC,"Snow White");
return ourDatabase.insert(DATABASE_TABLE,null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID,KEY_DESC};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns,null,null,null,null,null);
String result =" ";
int iRow = c.getColumnIndex(KEY_ROWID);
int iDescription = c.getColumnIndex(KEY_DESC);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result =result + c.getString(iRow)+ " " +c.getString(iDescription) +" \n";
}
return result;
}
main Activity.java
public class MainActivity extends Activity implements OnClickListener {
static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";
Button view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view =(Button) findViewById(R.id.viewSQL);
view.setOnClickListener(this);
}
//product qr code mode
public void scanQR(View v) {
try {
//start the scanning activity from the com.google.zxing.client.android.SCAN intent
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
} catch (ActivityNotFoundException anfe) {
//on catch, show the download dialog
showDialog(MainActivity.this, "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
}
}
//alert dialog for downloadDialog
private static AlertDialog showDialog(final Activity act, CharSequence title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo) {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
act.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return downloadDialog.show();
}
//on ActivityResult method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
//get the extras that are returned from the intent
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast toast = Toast.makeText(this, "Content:" + contents + " Format:" + format, Toast.LENGTH_LONG);
toast.show();
}
}
}
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.viewSQL:
Translator entry = new Translator(MainActivity.this);
entry.open();
entry.close();
Intent i = new Intent("com.example.scanner.SQLVIEW");
startActivity(i);
break;
}
}
SQLView.java
public class SQLView extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
TextView tv =(TextView) findViewById(R.id.tvSQLint);
Translator info = new Translator(this);
info.open();
String data = info.getData();
info.close();
tv.setText(data);
}
this is my error:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.scanner/com.example.scanner.SQLView}:
android.database.sqlite.SQLiteException: no such column: page_desc
(code 1):, while compiling: SELECT _id, page_desc FROM pageTable
What is my error?
Try this
public class Translator extends SQLiteOpenHelper {
private static final String LOGCAT = null;
public Translator(Context applicationcontext) {
super(applicationcontext, "androidsqlite.db", null, 1);
Log.d(LOGCAT, "Created Translator Database");
}
public static final String KEY_ROWID = "_id";
public static final String KEY_DESC = "page_desc";
private static final String DATABASE_TABLE = "pageTable";
private SQLiteDatabase ourDatabase;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " STRING PRIMARY KEY, " + KEY_DESC + " TEXT NOT NULL);");
}
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 long createEntry(String id, String description) {
ContentValues cv = new ContentValues();
cv.put(KEY_ROWID, id);
cv.put(KEY_DESC, description);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public long createEntry1(String id, String description) {
ContentValues cv = new ContentValues();
cv.put(KEY_ROWID, "P01");
cv.put(KEY_DESC, "Snow White");
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_DESC };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
String result = " ";
int iRow = c.getColumnIndex(KEY_ROWID);
int iDescription = c.getColumnIndex(KEY_DESC);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " "
+ c.getString(iDescription) + " \n";
}
return result;
}
}

when i tried to insert a row to database ,"table timeline has no column named source" occured"

I did have a column named source.I had no ideas where i was wrong.
I constructed table time at onCreate method.
public class DbHelper1 extends SQLiteOpenHelper {
static final String TAG = "DbHelper1";
static final String DB_NAME = "timeline.db";
static final int DB_VERSION = 1;
static final String TABLE = "timeline";
static final String C_ID = BaseColumns._ID;
static final String C_CREATED_AT = "created_at";
static final String C_SOURCE = "source";//C_SOURCE represents source
static final String C_TEXT = "txt";
static final String C_USER = "user";
Context context;
public DbHelper1(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
StringBuffer buffer = new StringBuffer();
buffer.append("create table " + TABLE + " (");
buffer.append(C_ID + " int primary key ,");
buffer.append(C_CREATED_AT + " int ,");
buffer.append(C_USER + " text ,");
buffer.append(C_TEXT + " text ,");
buffer.append(C_SOURCE+" text ");//here is my column source
buffer.append(")");
String sql=buffer.toString();
db.execSQL(sql);
Log.d(TAG, "onCreate sql :"+sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("drop table if exists "+TABLE);
Log.d(TAG, "onUpgrade");
onCreate(db);
}
}
here is my test service:
public class UpdaterService3 extends Service {
private static final String TAG = "UpdaterService3";
static final int DELAY = 3000;
private boolean runFlag = false;
private Updater updater;
private YambaApplication1 yamba;
DbHelper1 dbHelper;
SQLiteDatabase db;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
yamba = (YambaApplication1) getApplication();
this.updater = new Updater();
dbHelper = new DbHelper1(this);
Log.d(TAG, "onCreate");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
super.onStartCommand(intent, flags, startId);
this.runFlag = true;
this.updater.start();
this.yamba.setServiceRunning(true);
Log.d(TAG, "onStarted");
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
this.runFlag = false;
this.updater.interrupt();
this.updater = null;
this.yamba.setServiceRunning(false);
Log.d(TAG, "onDestroy");
}
private class Updater extends Thread {
public Updater() {
super("UpdaterService-Updater");
}
#Override
public void run() {
// TODO Auto-generated method stub
UpdaterService3 updaterService = UpdaterService3.this;
while (updaterService.runFlag) {
Status status;
Log.d(TAG, "Updater running");
try {
db=dbHelper.getWritableDatabase();
Log.d(TAG, "Updater ran");
status = new Status();
status.createdAt = String.valueOf(System
.currentTimeMillis());
status.id = UUID.randomUUID().toString();
status.source = "hello i'm " + status.id
+ ",nice to see you";
status.text = "wow baby :" + status.id;
status.user = "user:" + status.id;
ContentValues values = new ContentValues();
values.clear();
values.put(DbHelper1.C_ID, status.id);
values.put(DbHelper1.C_CREATED_AT, status.createdAt);
values.put(DbHelper1.C_SOURCE, status.source);
values.put(DbHelper1.C_TEXT, status.text);
values.put(DbHelper1.C_USER, status.user);
db.insertOrThrow(DbHelper1.TABLE, null, values);
Log.d(TAG, String.format("%s:%s", status.user,status.text));
db.close();
Log.d(TAG, "Updater run");
Thread.sleep(DELAY);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
updaterService.runFlag = false;
}
}
}
}
}
here is class status
public class Status {//entity bean
String id;
String createdAt;
String source;
String text;
String user;
}
I was really confused.I was a new coder for android.please help!~
1 DB_VERSION must be named DATABASE_VERSION. It's not an optional constant. If you modify the database structure in time, Android relies on this constant to perform the upgrades.
2 If you changed the database structure (i.e.: added or renamed a column), you must increase the DATABASE_VERSION constant value, in order for the onUpgrade() method to fire.

Sqlite inserting data with ListView

i wanted to append edit text value to in sqlitedb to the new text on top(index 0) and move the previously inserted data down(start from index 1) while inserting rows...Insert the new row on top and display them in a ListView. my code works for appending rows in the bottom .
help me out..
dbhelper.java
public class DBhelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "REGISTRATION_DB";
public static final String TABLE_NAME = "REGISTRATION_TABLE";
public static final int VERSION = 1;
public static final String KEY_ID = "_id";
public static final String NAME = "NAME";
public static final String DB = "create table " + TABLE_NAME + " ("
+ KEY_ID + " integer primary key autoincrement, " + NAME
+ " text not null );";
public DBhelper(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(DB);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
}
dataoperation.java
SQLiteDatabase database_ob;
DBhelper openHelper_ob;
Context context;
public Dataoper(Context c) {
// TODO Auto-generated constructor stub
context=c;
}
public Dataoper opnToRead() {
openHelper_ob = new DBhelper(context,
openHelper_ob.DATABASE_NAME, null, openHelper_ob.VERSION);
database_ob = openHelper_ob.getReadableDatabase();
return this;
}
public Dataoper opnToWrite() {
openHelper_ob = new DBhelper(context,
openHelper_ob.DATABASE_NAME, null, openHelper_ob.VERSION);
database_ob = openHelper_ob.getWritableDatabase();
return this;
}
public void Close() {
database_ob.close();
}
public long insertData(String fname) {
ContentValues contentValues = new ContentValues();
contentValues.put(openHelper_ob.NAME, fname);
opnToWrite();
long val = database_ob.insert(openHelper_ob.TABLE_NAME, null,
contentValues);
Close();
return val;
}
public Cursor readdata() {
String[] cols = { openHelper_ob.KEY_ID, openHelper_ob.NAME };
opnToWrite();
#SuppressWarnings("static-access")
Cursor c = database_ob.query(openHelper_ob.TABLE_NAME, cols, null,
null, null, null, null);
return c;
}
public Cursor queryAll(int nameId) {
String[] cols = { openHelper_ob.KEY_ID, openHelper_ob.NAME};
opnToWrite();
Cursor c = database_ob.query(openHelper_ob.TABLE_NAME, cols,
openHelper_ob.KEY_ID + "=" + nameId, null, null, null, null);
return c;
}
Mainactivity.java
public class MainActivity extends Activity {
ListView lv;
Dataoper adapter_ob;
DBhelper helper_ob;
SQLiteDatabase db_ob;
Button bt;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView)findViewById(R.id.list);
bt=(Button)findViewById(R.id.bt);
adapter_ob = new Dataoper(this);
String[] from = { DBhelper.NAME };
int[] to = { R.id.name };
cursor = adapter_ob.readdata();
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
R.layout.listitem_row, cursor, from, to);
lv.setAdapter(cursorAdapter);
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i= new Intent(MainActivity.this, Second.class);
startActivity(i);
}
});
}
}
You can display the values first which is inserted in last by query
select NAME from REGISTRATION_TABLE orderby _id ASEC
while executing this query,you get cursor values.from cursor value,you need to make arraylist and pass that arraylist to Arrayadapter.
Arraylist<String> al=new ArrayList<String>();
cursor cursor=db.rawquery("select NAME from REGISTRATION_TABLE orderby _id ASEC",null);
if(cursor.getcount()!=0)
{
cursor.movetofirst();
do{
al.add(cursor.getstring(0));
}
while(cursor.movetonext());
}
cursor.close();
Arrayadapter adapter=new Arrayadapter(this,R.layout.simple_list_item_1,al);
lv.setadapter(adapter);

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.

Categories