I'm trying to create table in the sqlite, but it is showing error that table cannot be created. I have a same code but the database and table name are different. the fields are same. Also one doubt. Can't i create the different table in the same database containing the same fields.
DbAdapter.java
the code is as below.
public class DbAdapter {
private static final String DATABASE_NAME="bible1";
private static final String DATABASE_TABLE="test1";
private static final int DATABASE_VERSION=1;
public static final String KEY_ID="_id";
public static final String UNITS="units";
public static final String CHAPTERS="chapters";
private static final String CREATE_DATABASE="create table test1 (_id integer primary key autoincrement, units text not null, chapters text not null);";
private SQLiteHelper sqLiteHelper;
private static SQLiteDatabase sqLiteDatabase;
private Context context;
//constructor
public DbAdapter(Context c){
context = c;
}
private static class SQLiteHelper extends SQLiteOpenHelper{
public SQLiteHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_DATABASE);
MakeUnits();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public DbAdapter open() throws SQLException{
try{
sqLiteHelper = new SQLiteHelper(context);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
}catch(NullPointerException ne){
Log.e("error in creating the table", "bye");
}
return this;
}
public void close(){
sqLiteHelper.close();
}
public static long MakeUnits()
{
ContentValues insert1 = new ContentValues();
insert1.put(UNITS, "Unit1");
insert1.put(CHAPTERS, "CHAPTER1");
return sqLiteDatabase.insert(DATABASE_TABLE,null,insert1);
}
public Cursor fetchAllNotes(){
return sqLiteDatabase.query(DATABASE_TABLE, new String[]{KEY_ID,UNITS,CHAPTERS}, null, null, null, null, null);
}
}
MainActivity.java
public class MainActivity extends ListActivity {
private DbAdapter Database;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listContent = (ListView) findViewById(android.R.id.list);
Database= new DbAdapter(this);
Database.open();
Cursor c = Database.fetchAllNotes();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
It is giving error when the open() method is called. Couldn't figure it out.
in the logcat the error in the tag is that "error in creating the table"
You're trying to call sqLiteDatabase.insert inside MakeUnits, but this sqLiteDatabase variable is null until after you call getWritableDatabase. You should pass db to MakeUnits and call insert on db, not on sqLiteDatabase.
database will be created only when you make a call to
getWritableDatabase()/getReadableDatabase()
If you do not have permissions for a writable db, you will get a readable
db.
public SQLiteDatabase getWritableDB() {
try {
return helper.getWritableDatabase();
} catch (Exception e) {
return getReadableDB();
}
}
public SQLiteDatabase getReadableDB() {
return helper.getReadableDatabase();
}
Related
I am facing this problem whenever i run the app 1st time data in database remain single time but when i close the App and restart again data goes twice(means two same row in table).Similarly for 3rd, 4th time and so on. How do i get rid of this problem? I even put datas.clear in DataList.java but don't whether i have add the datas.clear() line in correct place or not.
PLz help if there is any other problem in my code.
MainActivity.java code
public class MainActivity extends AppCompatActivity {
Button listButton, addButton;
DatabaseHelper df;
private final static String TAG = "TestActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
df = new DatabaseHelper(this);
addButton = (Button) findViewById(R.id.addbutton);
uploadList();
}
public void uploadList(){
DatabaseHelper df=new DatabaseHelper(this);
df.open();
try{
InputStream im=getResources().getAssets().open("testdata.csv");
BufferedReader br=new BufferedReader(new InputStreamReader(im));
String data=br.readLine();
while(data != null){
String t[]=data.split(",");
Product p=new Product();
p.setFirst(t[0]);
p.setSec(t[1]);
p.setThird(t[2]);
df.insert(p);
data=br.readLine();
}
}catch(Exception e){
}
}
}
DatabaseHelper.java code
public class DatabaseHelper extends SQLiteOpenHelper{
private static final String FIRST="Name";
private static final String SECOND="Issn";
private static final String THIRD="ImpactFactor";
private static final String DATABASE="journal2016";
private static final String TABLENAME="journal";
private static final int VERSION=1;
SQLiteDatabase sd;
public void open(){
sd=getWritableDatabase();
}
public void close(){
sd.close();
}
public DatabaseHelper(Context context) {
super(context, DATABASE, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLENAME );
sqLiteDatabase.execSQL("CREATE TABLE " + TABLENAME + " ( NAME TEXT, ISSN TEXT, IMPACTFACTOR REAL)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLENAME );
}
public long insert(Product p){
ContentValues cv=new ContentValues();
cv.put(FIRST, p.getFirst());
cv.put(SECOND, p.getSec());
cv.put(THIRD, p.getThird());
return sd.insertWithOnConflict(TABLENAME, null, cv,SQLiteDatabase.CONFLICT_REPLACE);
}
public List<Product> getAllProduct(){
ArrayList<Product> list=new ArrayList<Product>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c=db.rawQuery("SELECT * FROM " + TABLENAME, null);
while(c.moveToNext()){
Product p=new Product();
p.setFirst(c.getString(0));
p.setSec(c.getString(1));
p.setThird(c.getString(2));
list.add(p);
}
db.close();
return list;
}
}
DataList.java code
public class DataList extends Activity{
List<Product> datas = new ArrayList<Product>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
datas.clear();
DatabaseHelper d=new DatabaseHelper(this);
d.open();
datas = d.getAllProduct();
ListView lv=(ListView)findViewById(R.id.listView1);
lv.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, datas));
}
}
Product.java
public class Product {
private String first;
private String second;
private String third;
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSec() {
return second;
}
public void setSec(String sec) {
this.second = sec;
}
public String getThird() {
return third;
}
public void setThird(String third) {
this.third = third;
}
#Override
public String toString() {
return first + second + third;
}
}
Remove this line from your onCreate() method:
df = new DatabaseHelper(this);
as no need of it because you are create object of your DatabaseHelper class inside uploadList() method.
And also you are calling uploadList() method inside onCreate() thats why every time you launch the app, the onCreate() method executes and you uploadList() also execute. Try to put its calling statement in an onClickListener so it happens when you click a button or your choice of stuff.
I am working in android , and trying to insert values in database, here is the code of my database class
public class DataHandler {
public static final String fname="fname";
public static final String lname="lname";
public static final String age="21";
public static final String height="180";
public static final String weight="50";
public static final String TABLE_NAME="user";
public static final int DATABASE_VERSION=1;
public static final String DATA_BASE_NAME="SLIMART_DATABASE";
public static final String TABLE_CREATE ="create table user(fname text not null, lname text not null, age text not null, height text not null,weight text not null);";
DataBaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx)
{
this.ctx=ctx;
dbhelper=new DataBaseHelper(ctx);
}
private static class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context ctx)
{
super(ctx,DATA_BASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS user");
onCreate(db);
}
}
public DataHandler open()
{
db=dbhelper.getWritableDatabase();
return this;
}
public void close()
{
dbhelper.close();
}
public long insertData(String afname,String alname,String aage,String aheight,String aweight)
{
ContentValues content =new ContentValues();
content.put(fname,afname);
content.put(lname,alname);
content.put(age,aage);
content.put(height,aheight);
content.put(weight,aweight);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData()
{
return db.query(TABLE_NAME,new String[] {fname,lname,age,height,weight},null,null,null,null,null);
}
}
and here is the activity code from where I am accessing the database class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
save=(Button) findViewById(R.id.button1);
fname=(EditText) findViewById(R.id.fname);
lname=(EditText) findViewById(R.id.lname);
age=(EditText) findViewById(R.id.age);
height=(EditText) findViewById(R.id.height);
weight=(EditText) findViewById(R.id.weight);
save.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
String sfname=fname.getText().toString();
String slname=lname.getText().toString();
String sage=age.getText().toString();
String sheight=height.getText().toString();
String sweight=weight.getText().toString();
handler = new DataHandler(getBaseContext());
handler.open();
long id=handler.insertData(sfname, slname, sage, sheight, sweight);
Toast.makeText(getBaseContext(),"Data Successfully Saved",Toast.LENGTH_LONG).show();
handler.close();
}
});
}
but I recieve this error in logcat
03-22 03:16:37.060: E/AndroidRuntime(1115): android.database.sqlite.SQLiteException: near "0": syntax error (code 1): , while compiling: INSERT INTO user(lname,0,fname) VALUES (?,?,?)
content.put(age,aage);
content.put(height,aheight);
content.put(weight,aweight);
public static final String age="21";
public static final String height="180";
public static final String weight="50";
age, height and weight are not column names in your table but just numeric literals. Use actual column names as content keys. Also, you cannot have column names that are just numbers.
For example, change to:
content.put("age",aage);
content.put("height",aheight);
content.put("weight",aweight);
I checked your code & i saw the problem, this is your code to insert data.
public long insertData(String afname,String alname,String aage,String aheight,String aweight)
{
ContentValues content =new ContentValues();
content.put(fname,afname);
content.put(lname,alname);
content.put(age,aage);
content.put(height,aheight);
content.put(weight,aweight);
return db.insertOrThrow(TABLE_NAME, null, content);
}
-> Where: fname , lname , age, weight , height is field's name in database table. But you also define :
public static final String fname="fname";
public static final String lname="lname";
public static final String age="21";
public static final String height="180";
public static final String weight="50";
--> age,height , weight is not the name of field when you created database table.
SO: Please changed like this:
public static final String fname="fname";
public static final String lname="lname";
public static final String age="age";
public static final String height="height";
public static final String weight="weight";
I have a spinner. I want to load data from sqlite. I have try to load data with Activity class, it work but i want to load it in Fragment class and i got the method is undefined. There is any wrong ? What should i do ??
Sorry for my bad english..
This is Fragment class
public class InfoJadwal extends Fragment {
private DatabaseHandler dbhelper;
private SQLiteDatabase db = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dbhelper = new DatabaseHandler(getActivity());
db = dbhelper.getWritableDatabase();
dbhelper.delAllData(db);
dbhelper.generateData(db);
View rootView = inflater.inflate(R.layout.info_jadwal, container,
false);
loadDataSpinner();
return rootView;
}
private void loadDataSpinner() {
Cursor wisataCursor;
Spinner colourSpinner = (Spinner) getView().findViewById(
R.id.spin_tujuan);
wisataCursor = dbhelper.fetchAllWisata(db);
startManagingCursor(wisataCursor);
String[] from = new String[] { dbhelper.TUJUAN };
int[] to = new int[] { R.id.tvDBViewRow };
SimpleCursorAdapter wisataAdapter = new SimpleCursorAdapter(this,
R.layout.db_view_row, wisataCursor, from, to);
colourSpinner.setAdapter(wisataAdapter);
}
#Override
public void onDestroy() {
super.onDestroy();
try {
db.close();
} catch (Exception e) {
}
}
}
And this is class for DatabaseHandler.
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "medantrain";
public static final String TUJUAN = "tujuan";
public static final String KEY_ID = "_id";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, 1);
}
// method createTable untuk membuat table WISATA
public void createTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS KOTA");
db.execSQL("CREATE TABLE if not exists KOTA (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "TUJUAN TEXT);");
}
// method generateData untuk mengisikan data ke table Wisata.
public void generateData(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put(TUJUAN, "Binjai");
db.insert("KOTA", TUJUAN, cv);
cv.put(TUJUAN, "Rantau Prapat");
db.insert("KOTA", TUJUAN, cv);
cv.put(TUJUAN, "Tebing Tinggi");
db.insert("KOTA", TUJUAN, cv);
}
// method delAllAdata untuk menghapus data di table Wisata.
public void delAllData(SQLiteDatabase db) {
db.delete("KOTA", null, null);
}
public Cursor fetchAllWisata(SQLiteDatabase db) {
return db.query("KOTA", new String[] { KEY_ID, TUJUAN }, null, null,
null, null, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
replace
SimpleCursorAdapter wisataAdapter = new SimpleCursorAdapter(this,R.layout.db_view_row, wisataCursor, from, to);
with
SimpleCursorAdapter wisataAdapter = new SimpleCursorAdapter(getActivity(),R.layout.db_view_row, wisataCursor, from, to);
and replace
startManagingCursor(wisataCursor);
with
getActivity().startManagingCursor(wisataCursor);
but startManagingCursor(Cursor) in Activity is deprecated. see docs for more info http://developer.android.com/reference/android/app/Activity.html#startManagingCursor%28android.database.Cursor%29
SimpleCursorAdapter requires a Context reference but you are passing this which means a Fragment reference.
I have created DBAdapter class which is responsible for making a connection to a Database and does any query and finally close the connection.
I have another class which it is not inherited from Activity class(ReminderBeep), but i have to use my DBAdapter in this class.
Actually i don't know how can i manipulate the DBAdapter constructor to make the connection.*
The error is: The constructor DBAdapter(ReminderBeep) is undefined
DBAdapter is:
public class DBAdapter {
static final String DATABASE_NAME = "MyDB";
static final int DATABASE_VERSION = 2;
final Context context;
DatabaseHelper DBHelper;
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)
{
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public void insert(String sql)
{
db.execSQL(sql);
}
}
BeepReminder is:
public class ReminderBeep
{
public void DeleteDailyActivities()
{
DBAdapter db=new DBAdapter(this);
db.open();
String sql="delete from DailyWorks";
db.insert(sql);
db.close();
}
}
ReminderBeep is not extendig Activity. But DBAdapter want a Context as paramter,
DBAdapter db=new DBAdapter(this);
this refers to ReminderBeep
Hey guys I already have a data in my database but I want to show it into spinner I'm really new to this problem, so would you guys help me to solve this problem,or I would prefer if you write the correct code for me :) Thanks in advance.
First this is my DB class
public class DBAdapter
{
public static final String UPDATEDATE = "UpdateDate";
//Declare fields in PersonInfo
public static final String ROWID = "_id";
public static final String PT_FNAME = "Username";
public static final String PT_COLORDEF = "ColorDeficiency";
private static final String DATABASE_CREATE =
"create table PersonInfo (_id integer primary key autoincrement, "
+ "Username text not null, ColorDeficiency text);";
private static final String DATABASE_NAME = "CAS_DB";
private static final String tbPerson = "PersonInfo";
private static final int DATABASE_VERSION = 1;
private final Context databaseContext;
private final Context context;
private DatabaseHelper DBHelper;
public SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
databaseContext = ctx;
}
//start database helper
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public Cursor all(Activity activity){
String[] from ={ROWID,PT_FNAME,PT_COLORDEF};
String order = PT_FNAME;
Cursor cursor =db.query(tbPerson, from, null, null, null, null, order);
activity.startManagingCursor(cursor);
return cursor;
}
In another class
private DBAdapter db;
private Spinner spinner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.greeting);
initComponent();
db = new DBAdapter(this);
Cursor c = db.all(this);
SimpleCursorAdapter CursorAdapter = new SimpleCursorAdapter(
this,android.R.layout.simple_spinner_item,c,
new String[]{DBAdapter.PT_FNAME},new int[]{android.R.id.list});
CursorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(CursorAdapter);
try changing
new int[]{android.R.id.list}
to
new int[]{android.R.layout.simple_spinner_item}