Shubhankar
Shubhankar

Reputation: 95

Error while running SQLiteQuery

I am trying to save a score if it is no there. And if it's available then i need to get the highest score from the database.

SQLiteDatabase db= openOrCreateDatabase("tryitdb", MODE_PRIVATE, null);
            String sql= "create table if not exists tabletry(score int)";
            db.execSQL(sql);
            db.close();
            tv1= (TextView) findViewById(R.id.textView1);
            et1= (EditText) findViewById(R.id.editText1);
            b1 = (Button) findViewById(R.id.button1);
            b1.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    getsc();
                }
            });
        };
        public void getsc() {
            SQLiteDatabase db= openOrCreateDatabase("tryitdb", MODE_PRIVATE, null);
            String sql= "select * from tabletry";
            Cursor c1= db.rawQuery(sql, null);
            if(c1.isNull(0)){
                init();
            }
            else{
                int i1= c1.getColumnIndex("score");
                String l= c1.getString(i1);
                int old= Integer.valueOf(l);
                int str= Integer.valueOf(et1.getText().toString());
                if(old>=str){
                    tv1.setText(old);
                }
                else{
                    tv1.setText(str);
                }
            }

        }
        public void init() {
             SQLiteDatabase db= openOrCreateDatabase("tryitdb", MODE_PRIVATE, null);
             String string= "insert into tabletry values(?,?)";
             Object[] o= new Object[1];
             o[0] = et1.getText().toString();
             db.execSQL(string,o);
             db.close();
        }

The stacktrace tells me there is no such table as table try. Also gives me an error on the particular line

Cursor c1= db.rawQuery(sql, null);

Please suggest a fix to the issue. Thanks.

Upvotes: 0

Views: 63

Answers (2)

Nitin
Nitin

Reputation: 258

please manage your cursor.

  if (cursor != null && cursor.getCount() > 0) {

           c.moveToFirst(); 
                    // your logic goes here
                } else {
                    Toast.makeText(getApplicationContext(), "No Record Found", 1000).show();
                }

if you have several data then you can try

 if (cursor != null && cursor.getCount() > 0) {

   if (cur.moveToFirst()) {
  do {


    cur.getString(0); //any thing what you want to fetch

                    } while (cur.moveToNext());
                }}

Upvotes: 2

VenomVendor
VenomVendor

Reputation: 15382

Change >> db.equals(sql); to db.execSQL(sql);

Upvotes: 0

Related Questions