no columns in mysqlite database - java

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

Related

android.database.sqlite.SQLiteException: near "WHERE": syntax error (Sqlite code 1)

I would be grateful if anyone could help with this code
android.database.sqlite.SQLiteException: near "WHERE": syntax error (Sqlite code 1): , while compiling: SELECT * FROM WHERE category = 'B', (OS error - 2:No such file or directory)
error from debug
My DbHelper is as following
public class DbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Quiz.db";
private static final String KEY_ID = "id";
private static final String KEY_QUES = "question";
private static final String KEY_ANSWER = "answer"; //correct option
private static final String KEY_OPTA= "opta"; //option a
private static final String KEY_OPTB= "optb"; //option b
private static final String KEY_OPTC= "optc"; //option c
private static final String KEY_OPTD= "optd"; //option d
private static final String KEY_CAT="category"; //category
private static final String TABLE_QUEST1 = "questUnit1";
private SQLiteDatabase dbase;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
public DbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase=db;
String sql1 = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST1 + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_ANSWER+ " TEXT, "+KEY_OPTA +" TEXT, "
+KEY_OPTB +" TEXT, "+KEY_OPTC+" TEXT, "+KEY_OPTD+" TEXT, "+KEY_CAT+" TEXT)";
db.execSQL(sql1);
addQuestionsUnit1();
}
private void addQuestionsUnit1() {
QuestionUnit1 q101 = new QuestionUnit1("What is the decimal equivalent of the binary number 10111","21","23","39","42","23","B");
this.addQuestionsUnit1(q101);
QuestionUnit1 q102 = new QuestionUnit1("In order to write on a floppy disk with your IBM PC, you must first","digitize it","format it","compile it","hardware it","format it","B");
this.addQuestionsUnit1(q102);
QuestionUnit1 q249= new QuestionUnit1("Firewalls are used to protect against","Unauthorized Attacks","Viruses","Fire Attacks","Data Driven Attacks","Unauthorized Attacks","E");
this.addQuestionsUnit1(q249);
QuestionUnit1 q250= new QuestionUnit1("The first Digital Computer introduced, was named as ","UNIVAC","EDSAC","ENIAC","MARK-1","MARK-1","E");
this.addQuestionsUnit1(q250);
}
public void addQuestionsUnit1(QuestionUnit1 quest) {
//SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION1());
values.put(KEY_ANSWER, quest.getANSWER1());
values.put(KEY_OPTA, quest.getOPTA1());
values.put(KEY_OPTB, quest.getOPTB1());
values.put(KEY_OPTC, quest.getOPTC1());
values.put(KEY_OPTD, quest.getOPTD1());
values.put(KEY_CAT,quest.getCATEGORY1());
// Inserting Row
dbase.insert(TABLE_QUEST1, null, values);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public List<QuestionUnit1> getAllQuestions1(String tname, String lname)
{
List<QuestionUnit1> quesList1 = new ArrayList<QuestionUnit1>();
String selectQuery1 = "SELECT * FROM " + tname+" WHERE "+KEY_CAT+" = '"+lname+"'";
dbase=this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery1, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
QuestionUnit1 quest1 = new QuestionUnit1();
quest1.setID1(cursor.getInt(0));
quest1.setQUESTION1(cursor.getString(1));
quest1.setANSWER1(cursor.getString(2));
quest1.setOPTA1(cursor.getString(3));
quest1.setOPTB1(cursor.getString(4));
quest1.setOPTC1(cursor.getString(5));
quest1.setOPTD1(cursor.getString(6));
quesList1.add(quest1);
} while (cursor.moveToNext());
}
return quesList1;
}// end pubic list
}
the code walks like that a butto to To Exercise Activity
if(position == 2){
Intent i= new Intent(getApplicationContext(),Unit1ExerciseActivity.class);
i.putExtra("table_name",tableName);
i.putExtra("level_name","B");
startActivity(i);
overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
}
and the code in the exercise Activity is
public class Unit1ExerciseActivity extends AppCompatActivity {
List<QuestionUnit1> quesList1;
public int score=0;
int ctr1=1;
QuestionUnit1 currentQ1;
TextView txtQuestion1;
RadioGroup grp;
RadioButton rda1, rdb1, rdc1, rdd1;
Button butNext1;
Random random1 = new Random();
ArrayList<Integer> list = new ArrayList<Integer>();
TextView textViewTime1;
public ArrayList<String> wrongQuestListUnit1 = new ArrayList<String>();
public ArrayList<String> selectedAnsUnit1 = new ArrayList<String>();
public ArrayList<String> actualAnswerUnit1 = new ArrayList<String>();
int number;
ProgressBar progressBar;
int progress = 1;
String tableName="",catName="";
TextView qstnNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.unit1_exercise_activity);
qstnNo = (TextView)findViewById(R.id.qstnNo);
Intent iin=getIntent();
Bundle b=iin.getExtras();
if(b!=null){
tableName=(String)b.get("table_name");
catName=(String)b.get("level_name");
Log.d("Table Name",tableName);
Log.d("Level Name",catName);
}
number=0;
DbHelper db= new DbHelper(this);
textViewTime1 = (TextView)findViewById(R.id.textViewTime);
final CounterClass timer = new CounterClass(1800000, 1000);
timer.start();
quesList1=db.getAllQuestions1(tableName,catName);
for(int i=0;i<50;i++){
while(true){
int next = random1.nextInt(50);
if(!list.contains(next))
{
list.add(next);
break;
}
}
}
currentQ1=quesList1.get(list.get(0));
txtQuestion1=(TextView)findViewById(R.id.textView1);
rda1=(RadioButton)findViewById(R.id.radio0);
rdb1=(RadioButton)findViewById(R.id.radio1);
rdc1=(RadioButton)findViewById(R.id.radio2);
rdd1=(RadioButton)findViewById(R.id.radio3);
butNext1=(Button)findViewById(R.id.button1);
setQuestionView();
grp = (RadioGroup) findViewById(R.id.radioGroup1);
butNext1.setEnabled(false);
grp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if(i== R.id.radio0 || i == R.id.radio1 || i==R.id.radio2 || i == R.id.radio3)
butNext1.setEnabled(true);
}
});
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(30);
progressBar.setProgress(1);
butNext1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progress = progress+1;
progressBar.setProgress(progress);
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
//Log.d("yourans", currentQ1.getANSWER1() + " " + answer.getText());
if (currentQ1.getANSWER1().equals(answer.getText())) {
score++;
//Log.d("score", "Your score" + score1);
}
else
{
wrongQuestListUnit1.add(number, currentQ1.getQUESTION1());
selectedAnsUnit1.add(number, answer.getText().toString());
actualAnswerUnit1.add(number, currentQ1.getANSWER1());
number++;
}
grp.clearCheck();
butNext1.setEnabled(false);
if (ctr1 < 31) {
if (ctr1 == 30) {
butNext1.setText("End Test");
}
currentQ1 = quesList1.get(list.get(ctr1));
setQuestionView();
} else {
timer.onFinish();
timer.cancel();
}
}
});
}
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
textViewTime1.setText(hms);
}
#Override
public void onFinish() {
showResult();
}
}
public void showResult(){
Intent intent = new Intent(Unit1ExerciseActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("scoreUnit1 ", score);//Your score
b.putString("section",tableName);//Your table name
b.putString("category",catName);//Your category name
intent.putStringArrayListExtra("wrongQuestions", wrongQuestListUnit1);
intent.putStringArrayListExtra("selectedAnswer", selectedAnsUnit1);
intent.putStringArrayListExtra("actualAnswer", actualAnswerUnit1);
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
private void setQuestionView(){
txtQuestion1.setText(currentQ1.getQUESTION1());
rda1.setText(currentQ1.getOPTA1());
rdb1.setText(currentQ1.getOPTB1());
rdc1.setText(currentQ1.getOPTC1());
rdd1.setText(currentQ1.getOPTD1());
if(ctr1<10)
qstnNo.setText("0" + ctr1 + "/30");
else
qstnNo.setText("" + ctr1+ "/30");
ctr1++;
}
#Override
public void onBackPressed() {
//super.onBackPressed();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Uncomment the below code to Set the message and title from the strings.xml file
//builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
//Setting message manually and performing action on button click
builder.setMessage("If you close all your progress would not be saved... Do you wish to exit ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
//Creating dialog box
AlertDialog alert = builder.create();
//Setting the title manually
// alert.setTitle("CompQuiz");
alert.show();
}
}
You are probably passing/getting a null tableName.
Try this:
if(b!=null){
tableName=b.getString("table_name");
catName=b.getString("level_name");
Log.d("Table Name",tableName);
Log.d("Level Name",catName);
}
Try this please:
public void addQuestionsUnit1(QuestionUnit1 quest){
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION1());
values.put(KEY_ANSWER, quest.getANSWER1());
values.put(KEY_OPTA, quest.getOPTA1());
values.put(KEY_OPTB, quest.getOPTB1());
values.put(KEY_OPTC, quest.getOPTC1());
values.put(KEY_OPTD, quest.getOPTD1());
values.put(KEY_CAT,quest.getCATEGORY1());
// Inserting Row
dbase.insert(TABLE_QUEST1, null, values);
db.setTransactionSuccessful();
} catch (Exception e) {
Log.d("DB insertion", "Error while trying to add values to database");
} finally {
db.endTransaction();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public List<QuestionUnit1> getAllQuestions1(String tname, String lname)
{
List<QuestionUnit1> quesList1 = new ArrayList<QuestionUnit1>();
String selectQuery1 = "SELECT * FROM " + tname+" WHERE "+KEY_CAT+" = '"+lname+"'";
dbase= getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery1, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
QuestionUnit1 quest1 = new QuestionUnit1();
quest1.setID1(cursor.getInt(0));
quest1.setQUESTION1(cursor.getString(1));
quest1.setANSWER1(cursor.getString(2));
quest1.setOPTA1(cursor.getString(3));
quest1.setOPTB1(cursor.getString(4));
quest1.setOPTC1(cursor.getString(5));
quest1.setOPTD1(cursor.getString(6));
quesList1.add(quest1);
} while (cursor.moveToNext());
}
cursor.close();
return quesList1;
}
}

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

SQlite delete function is not deleting entries

Im having trouble getting individual items to delete in a database my application is using. I know the method gets called, but nothing in my list is ever removed. Im not getting any errors which is making it tough to track down. Assistance would be awesome.
public class MainActivity extends Activity{
//Global Variables
ListView lv;
Intent addM, viewM;
public DBAdapter movieDatabase;
String tempTitle, tempYear;
int request_Code = 1;
int request_code2 = 2;
SimpleCursorAdapter dataAdapter;
Cursor cursor;
Button addButton;
long testID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//creates the database
movieDatabase = new DBAdapter(this);
movieDatabase.open();
//movieDatabase.deleteAllMovies();
//creates the intents to start the sub activities
addM = new Intent(this, AddMovie.class);
viewM = new Intent(this, MovieView.class);
}
//handles the return of the activity addMovie
public void onActivityResult(int requestCode, int resultCode,
Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK)
{
switch(requestCode)
{
case 1:
dbAddMovie(data.getStringExtra("title"),
data.getStringExtra("year"));
break;
case 2:
testID = data.getLongExtra("rowid", -1);
dMovie(testID);
break;
}
}
}
//adds item to the movie list
public void dbAddMovie(String mT, String mY)
{
movieDatabase.open();
movieDatabase.insertMovie(mT, mY);
Toast.makeText(this, "Movie: " + mT + " added to database",
Toast.LENGTH_SHORT).show();
}
//deletes an entry into the database
public void dMovie(long rowid)
{
//Toast.makeText(this, "Deleting: " + rowid,
Toast.LENGTH_SHORT).show();
movieDatabase.deleteMovie(rowid);
movieDatabase.getAllMovies();
}
//displays the database as a list
public void displayListView()
{
addButton = (Button) findViewById(R.id.add);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(addM, 1);
}
});
cursor = movieDatabase.getAllMovies();
//columns to use
String[] columns = new String[]
{
movieDatabase.KEY_TITLE,
};
//xml data to bind the data to
int[] to = new int[]
{
R.id.column2,
};
//adapter to display the database as a list
dataAdapter = new SimpleCursorAdapter(this,
R.layout.complexrow, cursor, columns, to, 0);
//gets the List view resource
lv = (ListView) findViewById(R.id.movielist);
//sets the list view to use the adapter
lv.setAdapter(dataAdapter);
//handles the list click events
lv.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View
v, int position,
long id) {
Cursor cursor = (Cursor)
parent.getItemAtPosition(position);
Bundle mDet = new Bundle();
mDet.putString("title",
cursor.getString(cursor.getColumnIndex(movieDatabase.KEY_TITLE)));
mDet.putString("year",
cursor.getString(cursor.getColumnIndex(movieDatabase.KEY_YEAR)));
mDet.putInt("rId", position);
viewM.putExtras(mDet);
startActivityForResult(viewM, 2);
}
});
//dataAdapter.notifyDataSetChanged();
}
public void onResume()
{
super.onResume();
displayListView();
}
}
and my coresponding dbadapter class
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_YEAR = "year";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "MovieListDB";
private static final String DATABASE_TABLE = "MoviesTable";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "create table MoviesTable (_id
integer primary key autoincrement, " +
"title text not null, year not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(DATABASE_CREATE);
} catch (SQLException e)
{
e.printStackTrace();
}
}
#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 MoviesTable");
onCreate(db);
}
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close()
{
DBHelper.close();
}
public long insertMovie(String title, String year)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_YEAR, year);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteMovie(long rowID)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "='" + rowID+"'", null ) >-1;
}
public Cursor getAllMovies()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
KEY_YEAR}, null, null, null, null, null);
}
public Cursor getMovie(long rowID) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_YEAR}, KEY_ROWID + "=" + rowID, null, null, null, null, null);
if(mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateContact(long rowID, String title, String year)
{
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_YEAR, year);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowID, null) > 0;
}
public void deleteAllMovies() {
int doneDelete = 0;
doneDelete = db.delete(DATABASE_TABLE, null, null);
}
}
You're using the position returned from your listview as the row id in your database. This won't necessarily match up with your autoincremented "_id" in your database. position is just what position in the list it is.
You might want to think about using movieDatabase.KEY_ROWID as the key for your intents. Right now I see a mix of "rowid", "rId", "_id", and KEY_ROWID. It would simplify thing to just use the same key everywhere when referring to the same thing.
It looks like you continuously add bundles to the viewM intent. Is that true? If that's not your intent, you should either create a new intent for each click, or remove the previous bundles first.
I'm assuming KEY_ROWID is actually the name of the column? Try the following:
public boolean deleteMovie(long rowID)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=?", new String[] { String.valueOf(rowID) }) >-1;
}

why my first created row in database have id null1

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"?

Categories