It seems that SQLiteOpenHelper need pass Context parameter when I create a object, so I pass PublicPar.myContext=getApplicationContext() in Main (extends Activity).
But in IntentService, there isn't UI, and there isn't Activity, maybe I can't use getApplicationContext(). How can I operate SQLite when I use IntentService?
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
PublicPar.myContext=getApplicationContext();
RuleMain dBMainHelper=new RuleMain(PublicPar.myContext);
return dBMainHelper.ListAllRuleMain();
...
}
}
Helper:
package dal;
import java.util.ArrayList;
import java.util.List;
import model.MPublicPar.IncomingType;
import model.MRule;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class RuleMain extends SQLiteOpenHelper {
private final static String DBName="smsforwardrulemain.db";
private final static String TableRuleMain="rulemain";
public RuleMain(Context context) {
super(context, DBName, null, DBPublicPar.DBVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql = "Create table "
+ TableRuleMain
+ " (ruleID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ "enabled INTEGER NOT NULL,"
+ "incomingType INTEGER NOT NULL,"
+ "name TEXT NOT NULL"
+ ");";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
String sql=" DROP TABLE IF EXISTS "+TableRuleMain;
db.execSQL(sql);
onCreate(db);
}
public List<MRule> ListAllRuleMain(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+TableRuleMain, null);
List<MRule> myRuleMainList=GetMRuleListFromCursor(cursor);
cursor.close();
db.close();
return myRuleMainList;
}
}
Related
I have prepared a code to create a database as well as table in SQLITE ANDROID STUDIO, but I am getting error in SQL statement.
Image of error is here :- ERROR IMAGE
package com.example.thakkar.registration;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.view.View;
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DATABASAE_NAME="student.db";
public static final String TABLE_NAME="student_table";
public static final String COL_1="NAME";
public static final String COL_2="EMAIL";
public static final String COL_3="PASSWORD";
public DataBaseHelper(Context context) {
super(context, DATABASAE_NAME, null, 1);
SQLiteDatabase db=this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table"+ TABLE_NAME+ "(NAME TEXT,EMAIL TEXT,PASSWORD TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXIST"+ TABLE_NAME);
onCreate(db);
}
}
You need to separate table with space before TABLE_NAME,
Something like ,
db.execSQL("create table "+ TABLE_NAME+ "(NAME TEXT,EMAIL TEXT,PASSWORD TEXT)");
Also do the same in onUpgrade() method,
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
I'm new at the android studio. I tried creating SQLite Database but when I try inserting data android studio cannot resolve it. i also tried MainActivity.this and getApplicationContext instead of db=new DatabaseHelper(this); on this line. and on device monitor, it isn't creating a database file
MainActivity.java
package com.example.lenovo.sqlite_2_deneme;
import android.content.Context;
import android.media.midi.MidiDevice;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db=new DatabaseHelper(this);
EditText et_name,et_surname,et_number;
Button btn_data;
et_name= (EditText) findViewById(R.id.et_isim);
et_surname= (EditText) findViewById(R.id.et_soyisim);
et_number= (EditText) findViewById(R.id.et_numara);
btn_data= (Button) findViewById(R.id.btn_veri);
btn_data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.insertData();
}
});
}
}
and my DatabaseHelper class
package com.example.lenovo.sqlite_2_deneme;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;
import android.widget.TableLayout;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME= "student_info.db";
public static final String TABLE_NAME="student_table";
public static final String COL_1="ID";
public static final String COL_2="NAME";
public static final String COL_3="SURNAME";
public static final String COL_4="NUMBER";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE"+ TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, NUMBER INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+ TABLE_NAME);
this.onCreate(db);
}
public Boolean DataInsert(String name, String surname, String number)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,number);
long sonuc= db.insert(TABLE_NAME,null,contentValues);
if(sonuc==-1)
return false;
else
return true;
}
}
Your database will be created at the instance when you call
SQLiteDatabase db=this.getWritableDatabase();
At the moment I dont see you have called this anywhere in your code. You have written a DataInsert method but it is not getting called in the code you have shared so far.
your'e sql query is wrong give the space in table (insert data),and also in onupgrade and there is no method insertData()
db.execSQL("CREATE TABLE "+ TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, NUMBER INTEGER)");
There is no method insertData() . You should use
DataInsert() method .
db=new DatabaseHelper(MainActivity.this);
EditText et_name,et_surname,et_number;
Button btn_data;
et_name= (EditText) findViewById(R.id.et_isim);
et_surname= (EditText) findViewById(R.id.et_soyisim);
et_number= (EditText) findViewById(R.id.et_numara);
btn_data= (Button) findViewById(R.id.btn_veri);
btn_data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.DataInsert(et_name.getText().toString(),et_surname.getText().toString(),et_number.getText().toString());
}
});
FYI
void onCreate (SQLiteDatabase db)
Called when the database is created for the first time.
I am new to Android Programming.. I am trying to create sqLite Database in android Here is my code
sqLitee.java
package com.example.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class sqLitee extends SQLiteOpenHelper
{
public static final String DB_NAME="student.db";
public static final String TABLE_NAME="student";
public static final String COL_1="ID";
public static final String COL_2="FIRST_NAME";
public static final String COL_3="LAST_NAME";
public static final String COL_4="MARKS";
public sqLitee(Context context)
{
super(context, DB_NAME,null, 1);
// TODO Auto-generated constructor stub
SQLiteDatabase db=this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTO INCREMENT, FIRST_NAME TEXT, LAST_NAME TEXT, MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXIST " + TABLE_NAME);
onCreate(db);
}
}
MainActivity.java
package com.example.sqlite;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
sqLitee myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDB = new sqLitee(this);
setContentView(R.layout.activity_main);
}
}
When I am trying to run it on Android virtual Device , It says unfortunately , sqLite has stopped..
Thanks
remove this line in your sqllite constructor:
SQLiteDatabase db=this.getWritableDatabase();
you try to get the db, which is currently initializing.
There's a syntax error in your CREATE TABLE SQL. AUTO INCREMENT should be AUTOINCREMENT.
As always, first see the logcat for exception stacktrace and to learn what is failing and where.
My database class is DB.java
package com.example.pocketbooker;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
public class DB extends SQLiteOpenHelper implements BaseColumns{
private static final String DATABASE_NAME = "pb_database.db";
private static final int DATABASE_VERSION = 1;
public DB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE Members(_id INTEGER PRIMARY KEY AUTOINCREMENT, Mem_Name VARCHAR(50));");
db.execSQL("CREATE TABLE Incomes(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Inc_Name VARCHAR(50), Inc_Sum VARCHAR(10), Inc_Mem VARCHAR (50), Inc_Change_Date DATE, " +
"Inc_Perbeg_Date DATE, Inc_Period VARCHAR (4));");
db.execSQL("CREATE TABLE Outcomes(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Out_Name VARCHAR(50), Out_Sum VARCHAR(10), Out_Mem VARCHAR (50), Out_Change_Date DATE, " +
"Out_Perbeg_Date DATE, Out_Period VARCHAR (4));");
db.execSQL("CREATE TABLE Goals(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Goal_Name VARCHAR(50), Goal_Sum VARCHAR(10), Goal_Mem VARCHAR (50), Goal_Change_Date DATE, " +
"Goal_Perbeg_Date DATE, Goal_Period VARCHAR (4));");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
// TODO Auto-generated method stub
}
}
My "other" class is Dialog_mem.java
package com.example.pocketbooker;
import android.annotation.SuppressLint;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
#SuppressLint({ "NewApi", "ValidFragment" })
public class Dialog_mem extends DialogFragment implements OnClickListener {
EditText memname;
ContentValues cv = new ContentValues();
private SQLiteDatabase database;
private DB dbHelper;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().setTitle("Добавить Члена Семьи");
View v = inflater.inflate(R.layout.mem_dialog, null);
v.findViewById(R.id.mem_btnOK).setOnClickListener(this);
v.findViewById(R.id.mem_btnCancel).setOnClickListener(this);
memname=(EditText) v.findViewById(R.id.mem_name);
return v;
}
public void onClick(View v) {
switch(v.getId())
{ case R.id.mem_btnOK:
database = dbHelper.getWritableDatabase();
cv.put("Mem_Name", memname.getText().toString());
database.insert("Members", "Mem_Name", cv);
database.close();
Toast.makeText(getActivity(), "Добавлено", Toast.LENGTH_SHORT).show();
default:
dismiss();}
}
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
}
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
}
}
Eclipse shows NullPointerException. I guess it's context error, but I don't know how to point the context needed. getActivity() is the wrong one. "This" too. getApplicationContext() doesn't work at all.
You need to initialize the dbHelper instance.
What you can do is
1. Create a singleton class for all Database operations.
2. Create a Datasource class. Through which you will access the Database.
3. In Data Source class add open() method
/**
* Open the Database
* #throws SQLException
*/
public void open() throws SQLException {
if (dbHelper != null) {
db = dbHelper.getWritableDatabase();
}
}
/**
* Close
*/
public void close() {
dbHelper.close();
}
4. Write the method which you need to acces Database in DataSource class and call the database operations on this db instance.
Well, I used the akashsr's answer (thank you, man, for the idea). If anyone is interested how I've made it (at last) here's the code.
DB.java
package com.example.pocketbooker;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
public class DB extends SQLiteOpenHelper implements BaseColumns{
private static final String DATABASE_NAME = "pb_database.db";
private static final int DATABASE_VERSION = 1;
private static DB sInstance;
ContentValues cv;
public DB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE Members(_id INTEGER PRIMARY KEY AUTOINCREMENT, Mem_Name VARCHAR(50));");
db.execSQL("CREATE TABLE Incomes(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Inc_Name VARCHAR(50), Inc_Sum VARCHAR(10), Inc_Mem VARCHAR (50), Inc_Change_Date DATE, " +
"Inc_Perbeg_Date DATE, Inc_Period VARCHAR (4));");
db.execSQL("CREATE TABLE Outcomes(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Out_Name VARCHAR(50), Out_Sum VARCHAR(10), Out_Mem VARCHAR (50), Out_Change_Date DATE, " +
"Out_Perbeg_Date DATE, Out_Period VARCHAR (4));");
db.execSQL("CREATE TABLE Goals(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Goal_Name VARCHAR(50), Goal_Sum VARCHAR(10), Goal_Mem VARCHAR (50), Goal_Change_Date DATE, " +
"Goal_Perbeg_Date DATE, Goal_Period VARCHAR (4));");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
// TODO Auto-generated method stub
}
}
Created DataSource class with insert method. PBDataSource.java
package com.example.pocketbooker;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class PBDataSource {
DB dbHelper;
SQLiteDatabase db;
public PBDataSource(Context context) {
dbHelper = new DB(context);
}
public void open() throws SQLException {
if (dbHelper != null) {
db = dbHelper.getWritableDatabase();
}
}
public void close() {
dbHelper.close();
}
public void insertrecord (String a, String b, String c)
{ContentValues cv= new ContentValues();
cv.put(b,c);
db.insert(a, null, cv);
}
}
And used this method in my DialogFragment class Dialog_mem.java
package com.example.pocketbooker;
import android.annotation.SuppressLint;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
#SuppressLint({ "NewApi", "ValidFragment" })
public class Dialog_mem extends DialogFragment implements OnClickListener {
EditText memname;
private PBDataSource datasource;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().setTitle("Добавить Члена Семьи");
View v = inflater.inflate(R.layout.mem_dialog, null);
v.findViewById(R.id.mem_btnOK).setOnClickListener(this);
v.findViewById(R.id.mem_btnCancel).setOnClickListener(this);
memname=(EditText) v.findViewById(R.id.mem_name);
datasource = new PBDataSource(getActivity());
return v;
}
public void onClick(View v) {
switch(v.getId())
{ case R.id.mem_btnOK:
datasource.open();
datasource.insertrecord("Members","Mem_Name", memname.getText().toString());
datasource.close();
Toast.makeText(getActivity(), "Добавлено", Toast.LENGTH_SHORT).show();
default:
dismiss();}
}
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
}
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
}}
Of course, I'm a noob. I try to study myself as I can. And I hope it will help someone like me.
I want to make a Comment bar(an EditText) ,where one's comment will be added to SQLite DB and the comment will be shown in a ListView . I tried doing that but i ended up with a crashing application . On loading to Emulater it says. "Unfortunately ,SQLproj has stopped" . I am shraing what i did . Please help me with it. I am stuck with it since hours
My activity_main.xml (Layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<EditText
android:id="#+id/edittext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Please Share Your Valuable Reviews"
/>
<Button
android:id="#+id/button"
android:text="Submit"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
></ListView>
</LinearLayout>
My Pojo class
package com.example.sqlproj;
public class Comment {
public long id;
public String comment;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
#Override
public String toString()
{
return comment;
}
}
My SQLiteHelper class:
package com.example.sqlproj;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String Table_Name="Reviews";
public static final String DB_Name="Reviews";
public static final int DB_Version=1;
public static final String Column_Id="_id";
public static final String Column_Name="Comments";
public static final String DB_Create="create table" +Table_Name+ "(" +Column_Id+ "integer primary key autoincrement," +Column_Name+"text not null);";
public MySQLiteHelper(Context context) {
super(context, DB_Name, null, DB_Version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DB_Create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Application class:
package com.example.sqlproj;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class CommentsDataSource {
public SQLiteDatabase database;
public MySQLiteHelper dbhelper;
public String[] allcolumns= {dbhelper.Column_Id,dbhelper.Column_Name};
public CommentsDataSource(Context context)
{
dbhelper= new MySQLiteHelper(context);
}
public void open()
{
database = dbhelper.getWritableDatabase();
}
public void close()
{
dbhelper.close();
}
public Comment createComment(String comment)
{
ContentValues cv = new ContentValues();
cv.put(dbhelper.Column_Name, comment);
long id= database.insert(dbhelper.Table_Name, null, cv);
Cursor cursor = database.query(dbhelper.Table_Name, allcolumns, null, null, null, null, null);
cursor.moveToFirst();
Comment newcomment = commentSetter(cursor);
return newcomment;
}
public Comment commentSetter(Cursor cursor)
{
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setComment(cursor.getString(1));
return comment;
}
public List<Comment> getallComments()
{
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.query(dbhelper.Table_Name, allcolumns, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
Comment comment = commentSetter(cursor);
comments.add(comment);
cursor.moveToNext();
}
cursor.close();
return comments;
}
}
MAIN ACTIVITY CLASS
package com.example.sqlproj;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
public class MainActivity extends ListActivity {
public CommentsDataSource datasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> comments= datasource.getallComments();
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, comments);
setListAdapter(adapter);
}
public void onClick(View view)
{
Comment comment=null;
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
EditText edittext = (EditText) findViewById(R.id.edittext);
String com=edittext.getText().toString();
datasource.createComment(com);
adapter.add(comment);
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
add this onCreate(db) in below method. because without calling onCreate(db) your database is not created. because when you use SQLiteOpenHelper then onUpgrade method is called first.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
onCreate(db); // add this line
}
in MySQLiteHelper
fix this :
public static final String DB_Create="create table" +Table_Name+ "(" +Column_Id+ "integer primary key autoincrement," +Column_Name+"text not null);";
to this :
public static final String DB_Create = "create table " + Table_Name + "(" + Column_Id + " integer primary key autoincrement, " + Column_Name + " text not null " + );";