This code crashes the application, If i refer to database name from the static variable it works. When i try to get it from the strings.xml it crashes the app. Any idea why it fails? This is a class not an activity so i imported android.content.res.Resources. Also if i try context.getString it will also crash.
import android.content.Context;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
//public static final String DATABASE_NAME = "library.db";
public static final String TITLE = "title";
public static final String AUTHOR = "author";
public static final String ISBN = "isbn";
public DatabaseHelper(Context context) {
super(context, Resources.getSystem().getString(R.string.DATABASE_NAME), null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE books (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, author TEXT, isbn TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
You don't need to use a string resource for your database name, and in fact it doesn't make much sense to. String resources are mainly for anything the user will see so that you can provide alternative resources for other configurations (specifically, other languages). What you are providing is essentially a file name for your database. Since this is entirely internal to your app and the user will never see it, you should just use a static final String with the name you want for your database file.
/* Database file name */
private static final String BD_NAME = "something.db";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, null);
}
it is wrong
super(context, Resources.getSystem().getString(R.string.DATABASE_NAME), null, 1);
Try This
super(context, context.getResources().getString(R.string.DATABASE_NAME), null, 1);
change
Resources.getSystem().getString(R.string.DATABASE_NAME)
to
context.getResources().getString(R.string.DATABASE_NAME)
Related
I am trying to create a table in the Android SQLite database. But execSQLite method does not work in the on create method. It gives me the message-
Non-static method 'execSQL' cannot be a reference from a static context
But the method I am calling from is a non-static method.
The method is given below.
public void onCreate(SQLiteDatabase sqLiteDatabase) {
SQLiteDatabase.execSQL();
}
Here is my full java code:
package com.sarsinetvarneshon.basicdb;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Sarsinet Varneshon on 23-Apr-18.
*/
public class EmployeeDatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "db_employee";
public static final int VERSION = 1;
public static final String EMPLOYEE_TABLE_NAME = "tbl_employee";
public static final String EMPLOYEE_COL_ID = "id";
public static final String EMPLOYEE_COL_NAME = "name";
public static final String EMPLOYEE_COL_AGE = "age";
public static final String EMPLOYEE_COL_DEPT = "dept";
public static final String CREATE_TABLE_EMPLOYEE = " CREATE TABLE "+ EMPLOYEE_TABLE_NAME+
"("+EMPLOYEE_COL_ID+ " INTEGER PRIMARY KEY, "+
EMPLOYEE_COL_NAME+ " TEXT, "+
EMPLOYEE_COL_AGE+ " INT, "+
EMPLOYEE_COL_DEPT+ " TEXT)";
public EmployeeDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
SQLiteDatabase.execSQL();
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
Change the line:
SQLiteDatabase.execSQL();
To this line:
sqLiteDatabase.execSQL();
You are using a Class Name instead of the Variable.
You need to call sqLiteDatabase.execSQL(); not SqLiteDatabase.execSQL();
Because execSQL() method is not a static method, it needs to be called using an object from SQLiteDatabase, and it cannot be called using the class itself.
This is my main activity and I'm getting exception at 29th line of insertData() in MainActivity method and MyDatabaseAdapter() class contains the schema.Can u please help me with where I'm getting the error?
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
MyDatabaseAdapter myDatabaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText=(EditText)findViewById(R.id.editText);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name=editText.getText().toString();
long id=myDatabaseAdapter.insertData(name);
if(id<0)
{
Toast.makeText(MainActivity.this,"Unsuccessful",Toast.LENGTH_LONG);
}
else
{
Toast.makeText(MainActivity.this,"Successfull",Toast.LENGTH_LONG).show();
}
}
});
}
}
This is my sqlite helper class
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
public class MyDatabaseAdapter {
MyDatabase myDatabase;
MyDatabaseAdapter(Context context)
{
myDatabase=new MyDatabase(context);
}
public long insertData(String name)
{
SQLiteDatabase sqLiteDatabase=myDatabase.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(MyDatabase.NAME,name);
long id=sqLiteDatabase.insert(myDatabase.TABLE_NAME,null,contentValues);
return id;
}
static class MyDatabase extends SQLiteOpenHelper
{
private static final String DATABASE_NAME="Mydatabase";
private static final int DATABASE_VERSION=3;
private static final String TABLE_NAME="MyContacts";
private static final String NAME="Name";
// private static final String ADDRESS="Address";
private static final String UID="_id";
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+"("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+NAME+" VARCHAR(255),;";
private static final String DROP_TABLE="DROP TABLE IF EXISTS" +TABLE_NAME;
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Toast.makeText(context,"Constructor is called",Toast.LENGTH_LONG).show();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
}
}
you did not instantiate your MyDatabaseAdapter class. Try
myDatabaseAdapter = new MyDatabaseAdapter(this) after setContentView().
Firstly, you should really be able to give us more information. Your logcat output should show exactly what the error is or run with the debugger to catch the exception as it happens. Anyhow, with the info provided, at least one problem is that your create statement has invalid syntax. It evaluates as:
CREATE TABLE MyContacts(_id INTEGER PRIMARY KEY AUTOINCREMENT,Name VARCHAR(255),;
The comma and semi-colon are not required and there is no closing bracket. It should be:
CREATE TABLE MyContacts(_id INTEGER PRIMARY KEY AUTOINCREMENT,Name VARCHAR(255))
Or more correctly:
CREATE TABLE MyContacts(_id INTEGER PRIMARY KEY AUTOINCREMENT,Name TEXT)
...because there is no VARCHAR type in SQLite. Type affinity converts your VARCHAR(255) to TEXT because it contains the string 'CHAR' but it is best to specify SQLite types only to ensure you get what you expect.
Sorry if I'm talking something wrong, I'm still learning.
But in line 29, considering that you have 2 lines for thepackage and one break, this is the line:
shouldn't long be used for numbers ?
long id=myDatabaseAdapter.insertData(name);
"long: The long data type is a 64-bit two's complement integer. The
signed long has a minimum value of -263 and a maximum value of 263-1.
In Java SE 8 and later, you can use the long data type to represent an
unsigned 64-bit long, which has a minimum value of 0 and a maximum
value of 264-1. Use this data type when you need a range of values
wider than those provided by int. The Long class also contains methods
like compareUnsigned, divideUnsigned etc to support arithmetic
operations for unsigned long."
Am developing an android application in which i have created "Server" database. In that database i have two tables i,e employee_table and attendance_table in that i hav not included my onReceive function and with that onReceive function i need to parse the new message and that message content should be store in employee table and attendance table so please me out to solve this issue..
Thanks in advance..
Here is my DbHelper.java :
package com.example.attendancesystem;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="Server";
public static final String EmployeeTable="employee_table";
public static final String Name="name";
public static final String Mobile_no="mobile";
public static final String Id="id";
public static final String AttendanceTable="attendance_table";
public static final String Latitude="Lat";
public static final String Longitude="Lan";
public static final String Accuracy="Accry";
public static final String Date="date";
public static final String Time="time";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+EmployeeTable+" ("+Id+" INTEGER PRIMARY KEY, "+Name+" TEXT, "+Mobile_no+" VARCHAR(13))";
db.execSQL(CREATE_TABLE);
CREATE_TABLE="CREATE TABLE "+AttendanceTable+" ("+Latitude+" double precision, "+Longitude+" double precision, "+Accuracy+" double,"+Date+" date,"+Time+"time)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+EmployeeTable);
db.execSQL("DROP TABLE IF EXISTS "+AttendanceTable);
onCreate(db);
}
}
This is my code,my database doesn't show in file explorer.does i make mistake??can anyone have a solution??
I'm sorry because im just beginner in android
package com.testmysqlite.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class MySqliteOpenHelper extends SQLiteOpenHelper {
private static String dbName = "TestDatabase.db";
private static String tableName = "User";
private static String columnId = "Id";
private static String columnName = "Name";
private String sql = "create table "+tableName+"("+columnId+" integer,"+columnName+" text)";
private SQLiteDatabase sqliteDatabase = null;
public MySqliteOpenHelper(Context context) {
super(context, dbName, null, 1);
sqliteDatabase = getWritableDatabase();
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(sql);// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Take a look at this:link
link2
I have 2 text fields on the screen and a button. When the button is pressed I want the information in the name text field to be passed to a variable, then run my addAccount() method in my DatabaseHelper.class, passing the variable into this method, this should store the variable information in an SQLite database.
Here is my Activity with the text field and button.
package mr.mwod.moneyorganiser;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddAccountActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addaccountlayout);
Button addAccountVairiable = (Button) findViewById(R.id.addAccountButton);
addAccountVairiable.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText accountNameData = (EditText)findViewById(R.id.accountNameTextField);
String accountNameVairiable = accountNameData.getText().toString();
//Need the code here to run addAccount form DatabaseHelper.class
//accountName vairiable needs to be passed into the method as the information to store.
}
});
}
}
I have commented where I think the code needs to go and what it needs to do.
Here is my DatabaseHelper.class encase their are errors is in there.
package mr.mwod.moneyorganiser;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "money_organiser";
private static final String TABLE_ACCOUNTS = "accounts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "account_name";
private static final String KEY_ACCOUNT_BALANCE = "account_balance";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_ACCOUNTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_ACCOUNT_BALANCE + " INTEGER" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ACCOUNTS);
// Create tables again
onCreate(db);
}
public void addAccount(String name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name);
db.insert(TABLE_ACCOUNTS, null, values);
db.close();
}
}
Any help would be greatly appreciated.
Is there any trick in your question? Isn't just calling new DatabaseHelper(this).addAccount(accountNameVairiable); working? Of course it will make sense to reuse the variable, rather than allocating it every time, but I am almost sure this is not your problem.
By the way I would recommend you to change the name of the primary key column of the table. Use _id, some android helper methods will be easier to use in this way.
EDIT: I just noticed the call happens in anonymous class. This as noted by you will trigger a compilation error, because the listener is not a Context. The activity is. Luckily this can be very easily solved via placing what class exactly to use for the ocnstruction (using the parent Activity, which is a context).
new DatabaseHelper(AddAccountActivity.this).addAccount(accountNameVairiable);
It looks as if all you are missing is a call to DatabaseHelper.addAccount() at the lines you have highlighted.
Does this not work? If you are getting an error, then tell us what the problem is.
If you are wondering how to access the DatabaseHelper, then you could make it a singleton and refer to its instance when needed.