need help developing a quiz app for android - android

I am trying to develop a quiz app for physics, but I keep getting the error
02-23 16:02:06.006: E/Database(9348): on sqlite3_open_v2("data/data/com.mcq.srm/databases/q.db", &handle, 1, NULL) failed
Code Snippet below
public class QuestionPane extends Activity {
int counter =00;
RadioButton radioButton;
TextView Question;
TextView tvScore;
Button Next;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionpane);
int resdb=0;
try {
SQLiteDatabase checkDB = null;
String DB_FULL_PATH = "data/data/com.mcq.srm/databases/q.db";
checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
//Toast.makeText(this,"db "+checkDB, Toast.LENGTH_LONG).show();
resdb=0;
Log.v("msg","Database created");
} catch (Exception e){
resdb=1;
}
Log.v("msg", "check res-->"+resdb);
try{
db = openOrCreateDatabase("q.db" , SQLiteDatabase.CREATE_IF_NECESSARY , null );
if(resdb==1)
{
Log.v("msg","creating tables");
CreateTable();
InsertData();
displayres();
}
}
catch(Exception e){
}
}
public void CreateTable(){
String Createtab;
Createtab =" CREATE TABLE tbl_Question ("+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, Questions TEXT, option_1 TEXT,option_2 TEXT, option_3 Text, option_4 TEXT, correct_answer TEXT);";
try{
db.execSQL(Createtab);
}
catch(Exception e){
}
}
public void InsertData(){
ContentValues values = new ContentValues();
values.put("question", "Two beams of red and violet colours are made to pass separately through a prism of A = 60°. In the minimum deviation position, the angle of refraction inside the prism will be");
//... value.put statements removed
db.insert("tbl_Question", null, values);
//.. values.put statements removed
values.put("correct_answer","35 grams");
db.insert("tbl_Question", null, values);
}
public void displayres() {
int qno=1;
String sql1="select * from question;";
Cursor c1=db.rawQuery(sql1,null);
Log.v("answer","asd");
String que,opt1,opt2,opt3,opt4;
startManagingCursor(c1);
c1.moveToFirst();
que=c1.getString(c1.getColumnIndex("Question1"));
Log.v("answer",que);
}
}

There are lot of mistakes in your I'll suggest you go through this example, it's best to start with that example in android.You need to create separate class for Database generally know as Database Adapter and one more that is Database Helper by Android Devs. So to get complete idea go through that example.

Related

I add 3 records in sqlitedatabase, but then when I want to add some new record the sqlitedatabase don't show me the new records

In my first run, I created 3 record and that worked nice!
But when I thought to add a new record and wanted all the 4(3+1) record to be Toasted, it only Toast the 3 past records!
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
SQLiteDatabase sqLiteDatabase = this.openOrCreateDatabase("Database", MODE_PRIVATE, null);
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS database(name VARCHAR,age INT(3))");
sqLiteDatabase.execSQL("INSERT INTO database(name,age) VALUES('ARGHA',20)");
sqLiteDatabase.execSQL("INSERT INTO database(name,age) VALUES('CHANDRA',21)");
sqLiteDatabase.execSQL("INSERT INTO database(name,age) VALUES('DHAR',22)");
sqLiteDatabase.execSQL("INSERT INTO database(name,age) VALUES('AMIT',26)");
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM database", null);
cursor.moveToFirst();
int nameIndex = cursor.getColumnIndex("name");
int ageIndex = cursor.getColumnIndex("age");
while (cursor != null) {
Toast.makeText(this, cursor.getString(nameIndex) + ":" + Integer.toString(cursor.getInt(ageIndex)), Toast.LENGTH_SHORT).show();
cursor.moveToNext();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Cannot connect to MSSQL database from android

This is the code of my Connection Class, but the connection is not getting established. Whenever I print con I get null , Can anyone tell me where I went wrong? I included the jtds-1.3.1.jar in lib folder of app. I am unable to understand where I went wrong
package com.jazzitup.music;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.*;
import net.sourceforge.jtds.jdbc.*;
public class ConnectionClass {
#SuppressLint("NewApi")
public static Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:sqlserver://jazzitup.database.windows.net:1433;database=jazzitup.db;user=xxxxxxxx;password=xxxxxx;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
System.out.println("CON:"+conn);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
}
It's preferable (or a must i think) to use web services to access your data base from the device and not using a direct connection . Not every lib for java works with andoid .
1.First of all make class that extend SQLiteOpenHelper
2.Create a contractor for that class and implement all the function that needed .
On the method
onCreate((SQLiteDatabasedb)
Just create String called query
and create the table you want , and execSql it , for example :
String query="create table if not exists table(text text,name text2,_id text)";
db.execSQL(query);
Then for create new row in the sql lite use :
public void add_new_row(String text,String text2,String _id){
try{
ContentValues cn=new ContentValues();
cn.put("text",per_name);
cn.put("text2",per_age);
cn.put("_id",per_age);
SQLiteDatabase db;
db=getWritableDatabase();
db.insert("table",null,cn);}
catch(Exception e){
Log.i("AddSql_lite","Print :"+e.to );
}
And for read Row from sqllite you just use :
public String getRow_by_id(String _id){
string text = "";
try{
db=getWritableDatabase();
query="select * from table where _id = '"+_id+"'";
Cursor cr=db.rawQuery(query, null);
if(cr.moveToFirst()){
do{
text = cr.getString(0);
String text2 = cr.getString(1);
String _id = cr.getString(2);
}while(cr.moveToNext());
}
}catch(Exception e){
}
return text;
}
And for reading all the rows in the table one after another :
public int get_all_Rows(){
string int counter = 0;
try{
db=getWritableDatabase();
query="select * from table";
Cursor cr=db.rawQuery(query, null);
if(cr.moveToFirst()){
do{
text = cr.getString(0);
String text2 = cr.getString(1);
String _id = cr.getString(2);
counter++;
}while(cr.moveToNext());
}
}catch(Exception e){
}
return counter;
}
Hope its will help you to understand how Sqllite work and how build it correctly :)
And for make it run so just :
SQLiteDataBase Sqllite_ref = new SQLiteDataBase(context, "VerName",
null, 1);
Sqllite_ref.add_new_row("hey","hey4","1");
Sqllite_ref.add_new_row("hey2","hey5","2");
Sqllite_ref.add_new_row("hey3","hey6","3");
Sqllite_ref.getRow_by_id("2");>>> will return "hey2"
Sqllite_ref.get_all_Rows()>>> will return 3 [number of items you have
in the sqllite]

DatabaseLocked exception even after closing with db.close() and db.setTransactionSuccessful()

The application am working on will initially have one database with a table, say tbl_usr which will have only one record. Basically we are trying to keep one user per device. When the user logs in from the device with an auth code, his details will be fetched from server and stored in database. Next time if he tries to enter different auth code, which is valid but is not in table then he will not be allowed to proceed. Below is a common DBHelper class.
But whatever approach am trying, I am getting databaselocked exception, when tried for the 2nd time login. I've referred various links where in it was suggested to use different instance of database within method, but still it comes with error. Below is my Helper class
public class DBaseHelper extends SQLiteOpenHelper {
private static String CREATE_TABLE;
private static final String DATABASE_NAME="IPDB";
private static String UserMessage="";
private int tableType=0;
private ContentValues cValues;
private Cursor cursor;
public enum TableTypes{
Table1
};
public DBaseHelper(Context context){
super(context,context.getExternalFilesDir(null).getAbsolutePath()+"/"+DATABASE_NAME,null,1);
}
#Override
public void onCreate(SQLiteDatabase db){
TableTypes tableTypes=TableTypes.values()[tableType];
switch (tableTypes){
case Table1:
CREATE_TABLE="CREATE TABLE IF NOT EXISTS tbl_usr....";
break;
default:
break;
}
db.execSQL(CREATE_TABLE);
db.close();
System.out
.println("onCreate Method Done.");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
/*db.execSQL("DROP TABLE IF EXISTS "+LOGIN_TABLE);*/
onCreate(db);
}
/*this is the method which gets called from other class Like*/
/*helper.insertRecord(tableParams);*/
public HashMap<String,String> insertRecord(HashMap<String,String> dbaseParams){
HashMap<String,String> response=new HashMap<String,String>();
tableType=Integer.parseInt(dbaseParams.get("tableType"));
cValues = new ContentValues();
String TableName="";
TableTypes tableTypes=TableTypes.values()[tableType];
switch (tableTypes){
case Table1:
String AuthCode=dbParams.get("AuthCode");
/*if user exists then check if its the same user*/
if( CheckUserRecordExists(AuthCode) && empty(UserMessage) ){
response.put("isSuccess","true");
return response;
}
else {
if (!empty(UserMessage)) {
response.put("isSuccess", "false");
response.put("message",UserMessage);
return response;
}
/*add new user
Fill cValues declared above*/
TableName = "Table1";
}
break;
default:
break;
}
SQLiteDatabase dataBase = getWritableDatabase();
/*insert data into database*/
try {
dataBase.beginTransaction();
long rowID = dataBase.insertOrThrow(TableName, null, cValues);
dataBase.setTransactionSuccessful();
}
catch(Exception ex){
ex.printStackTrace();
}
finally {
dataBase.close();
}
response.put("isSuccess", "true");
return response;
}
private boolean CheckUserRecordExists(String authCode){
UserMessage="";
SQLiteDatabase dataBase=getReadableDatabase();
/*Exception here when comes for 2nd time after new installation*/
cursor = dataBase.query("Table1", new String[]{"COUNT(*)"}, null, null, null, null, null);
cursor.moveToFirst();
int iCount=cursor.getInt(0);
/*check if any record exist*/
if(iCount>0){
dataBase.close();
if(!cursor.isClosed()) cursor.close();
/*check if the code entered matches with the record existing*/
if(!CheckIsDataAlreadyInDBorNot("Table1","Auth_Code",authCode))
{
UserMessage="Invalid login!";
return false;
}
else return true;
}
else{
dataBase.close();
if(!cursor.isClosed()) cursor.close();
return false;
}
}
private boolean CheckIsDataAlreadyInDBorNot( String TableName,
String dbfield, String fieldValue) {
/*checking if user is same user*/
SQLiteDatabase dataBase=getReadableDatabase();
String[] columns = { dbfield };
String selection = dbfield + " =?";
String[] selectionArgs = { fieldValue };
String limit = "1";
Cursor cursor = dataBase.query(TableName, columns, selection, selectionArgs, null, null, null, limit);
boolean exists = (cursor.getCount() > 0);
cursor.close();
dataBase.close();
return exists;
}
public static boolean empty( final String s ) {
return s == null || s.trim().isEmpty();
}
}
I know its a huge code, but logic is simple. But the problem is database lock. Could someone let me know how I can make sure that database is always in valid state on each operation?
You have beginTransaction() but no matching calls to endTransaction(). An ongoing transaction keeps the database in a locked state and also keeps the internal reference count nonzero, so close() does not yet actually close the database.
The conventional pattern for transactional operations is
db.beginTransaction();
try {
// db operations that can throw
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Also in your onCreate() you should not be closing the database since you don't own it.

how to insert data into an sq-lite database at runtime [duplicate]

This question already exists:
how to insert data into sq-lite database at run-time [closed]
Closed 9 years ago.
I built an application that uses sq-lite database and within the application at run-time i made a button that when pressed added a new Edit-Text i'm wondering how can i save the values in the new Edit-Text into my database? please help me
Use this method :
public long saveData(Context context, String editTextValue) {
long x = -1;
appDb = new AppDatabase(context);
sqliteDb = appDb.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("monthOfBirth", editTextValue);
try {
if (sqliteDb.isOpen()) {
x = sqliteDb.insert("password", null, values);
if (x >= 0)
{
Toast.makeText(context, "Password Save", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception exc) {
exc.printStackTrace();
}
return x;
}
Call this method in your button's onClickListener()
button.setOnCLickListener(new View.OnClickListener())
{
#override
public void onClick(View v)
{
if(editText.getText().toString.equals(""))
{
Toast.makeText(context, "Fill Value first.", Toast.LENGTH_SHORT).show();
return;
}
saveData(YourActivity.this, editText.getText().toString());
}
}
Have you created the class extending SQLiteOpenHelper? If you have it, then use the constructor and get an object of this class:
dbHelper = new SQLiteHelper(context, getString(R.string.db_name_dev), null, DB_VERSION);
And then for example:
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("term", term);
db.insert("Search", null, cv);
Simply make a String which contains insert query of SQL. Then call the method
db.execSQL(sql);
on your datebase refence variable.
String sql =
"INSERT INTO <TABLE_NAME> VALUES('this is','03/04/2005','5000','tran','y')" ;
db.execSQL(sql);

display primary key after inserting in database

I am developing an android app, and i want to display the primary key in the textview so that every-time I edit a textfield, I will be using the primary key to update.can anyone help me with this? below is the inserting of data in the sqlite. My problem is how to get the primary key...
public class UsedataActivity extends Activity {
DatabaseHandler db = new DatabaseHandler(this);
ImageButton evsave;
EditText evname;
EditText evtime;
EditText evdate;
EditText evcode;
TextView evadmin;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onetoone);
evsave = (ImageButton)findViewById(R.id.event_save);
evname = (EditText)findViewById(R.id.eventname);
evtime = (EditText)findViewById(R.id.time1);
evdate = (EditText)findViewById(R.id.eventdate);
evcode = (EditText)findViewById(R.id.eventcode);
evadmin = (TextView)findViewById(R.id.adminname_1to1);
evsave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Events addev =
new Events(evname.getText().toString(),evcode.getText().toString(),evdate.getText().toString(),Integer.parseInt(evtime.getText().toString()),evadmin.getText().toString());
db.addEvents(addev);
Toast.makeText(getApplicationContext(), "Event: "+ evname.getText()+" successfully save",
Toast.LENGTH_SHORT).show();
}
});
}
database handler class:
public void addEvents(Events event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EV_NAME, event.get_name());
values.put(KEY_EV_PASS, event.get_pass());
values.put(KEY_EV_DATE, event.get_date());
values.put(KEY_EV_TIME, event.get_time());
values.put(KEY_EV_ADMIN, event.get_admin());
// Inserting Row
db.insert(TABLE_EVENTS, null, values);
db.close();
}
As it can be observed from the docs for the SQLiteDatabase, db.insert will return the id of the newly created object. Just make addEvents return it (instead of being `void).
PS: Please paste code in edits of the question, not in comments. In comments they really look awful!
EDIT
public long addEvents(Events event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EV_NAME, event.get_name());
values.put(KEY_EV_PASS, event.get_pass());
values.put(KEY_EV_DATE, event.get_date());
values.put(KEY_EV_TIME, event.get_time());
values.put(KEY_EV_ADMIN, event.get_admin());
// Inserting Row
long id = db.insert(TABLE_EVENTS, null, values);
db.close();
return id;
}
And then:
long id = db.addEvents(addev);
Toast.makeText(getApplicationContext(),
"Event with id: "+ id + " successfully saved",
Toast.LENGTH_SHORT).show();

Categories

Resources