i am learning sqlite from slidenerd. Following all as mention in tutorials but getting issue.
Constructor is working properly but oncreate is not working.
Openhelper class code
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Kamisqlhelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="kamidatabase";
public static final String TABLE_NAME="kamitable";
public static final int DATABASE_VERSION=1;
private static final String id="_id";
private static final String names="Name";
private static final String contact="PhoneNo";
private static final String CREATE_TABlE = "create table "+TABLE_NAME+"("+id+" integer primary key autoincrement, "+names+" varchar(255), "+contact+" integer);";
private static final String droptable= "drop table "+TABLE_NAME+" if exists";
private Context context;
public Kamisqlhelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context=context;
toastmessage.showtoast(context, "constructor called");
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try {
db.execSQL(CREATE_TABlE);
} catch (SQLException e) {
// TODO Auto-generated catch block
toastmessage.showtoast(context, ""+e);
toastmessage.showtoast(context, "oncreate called");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
try {
db.execSQL(droptable);
onCreate(db);
} catch (SQLException e) {
// TODO Auto-generated catch block
toastmessage.showtoast(context, ""+e);
toastmessage.showtoast(context, "onupgradecalled");
}
}
}
Main activity code
import android.os.Bundle;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
public class MainActivity extends Activity {
Kamisqlhelper kamihelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kamihelper = new Kamisqlhelper(this);
SQLiteDatabase sqLiteDatabase = kamihelper.getWritableDatabase();
}
}
please also suggest better up to date tutorial on sqlite.
onCreate is called when the database is created for the first time, that means when you first use the SQLiteOpenHelper,it will be called, otherwise,it never be called SQLiteOpenHelper.html#onCreate
Related
I have written a piece of code, which populates a database. However, when i execute that code in my android device or emulator, it gives an error "sorry app1 has stopped working" Please help me out to find out what's wrong.
the MainActivity.java file
package cu_coders.app1;
import android.net.Uri;
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.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
public final EditText e=(EditText)findViewById((R.id.text1));
public final file1 f=new file1();
TextView t=(TextView)findViewById(R.id.textView1);
final myDB x=new myDB(this, null, null, 1);
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
Button enter=(Button)findViewById(R.id.button1);
Button delete=(Button)findViewById(R.id.button2);
enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = e.getText().toString();
f.set_name(s);
x.addItem(f);
t.setText(x.printTable());
}
});
}
}
A CLASS NAMED FILE1.JAVA
package cu_coders.app1;
/**
* Created by user pc on 03-10-2016.
*/
public class file1 {
private int _roll;
private String _name;
public file1() {
}
public file1(String _name) {
this._name = _name;
}
public int get_roll() {
return _roll;
}
public String get_name() {
return _name;
}
public void set_roll(int _roll) {
this._roll = _roll;
}
public void set_name(String _name) {
this._name = _name;
}
}
THE CLASS FOR DATABASE MANAGEMENT-- myDB.java
package cu_coders.app1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by user pc on 03-10-2016.
*/
public class myDB extends SQLiteOpenHelper {
private static int DATABASE_VERSION=1;
private static String DATABASE_NAME="file.db";
private static String TABLE_FILE1="class_cse";
public static String COLUMN_KEY="_key";
public static String COLUMN_NAME="_name";
public myDB(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query="create table "+ TABLE_FILE1 + "(" +
COLUMN_KEY + " INTEGER PRIMARY KEY "+
COLUMN_NAME+" TEXT "+
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FILE1+";");
onCreate(db);
}
public void addItem(file1 f){
ContentValues cv=new ContentValues();
cv.put(COLUMN_NAME,f.get_name());
SQLiteDatabase db=getWritableDatabase();
db.insert(TABLE_FILE1,null,cv);
db.close();
}
/*public void deletItem(String item){
SQLiteDatabase db=getWritableDatabase();
db.execSQL("DELETE FROM "+TABLE_FILE1+" WHERE "+COLUMN_NAME+" =\" "+ item +"\";");
db.close();
} */
public String printTable(){
String dbstring="";
SQLiteDatabase db=getWritableDatabase();
String query="SELECT * FROM "+TABLE_FILE1+" WHERE 1;";
Cursor c=db.rawQuery(query,null);
c.moveToFirst();
while(!c.moveToLast()){
if(c.getString(c.getColumnIndex(COLUMN_NAME))!=null) {
dbstring += c.getString(c.getColumnIndex(COLUMN_NAME));
dbstring += '\n';
}
}
db.close();
return dbstring;
}
}
please help me out to find out what is wrong. thank you in advance.
you should change several items i guess...
change myDB Constructor to this :
public myDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
and in mainActivity class change all global variable like this :
private EditText e ;
private file1 f ;
private TextView t;
and in oncreate() initial them :
e=(EditText)findViewById((R.id.text1));
f=new file1();
t=(TextView)findViewById(R.id.textView1);
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.
I have to create tables using sqlopenhelper. When I'm running the app in the emulator, the code is not giving error, but a log message from table creation is being shown. When I try to register the app stops.
I've used the following code:
package com.example.catchthebus;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbHelp extends SQLiteOpenHelper {
SQLiteDatabase db;
public static String DB="CatchTheBus";
public static final String Table_name="Driver";
public static final String Driver_ID="Driver_ID";
public static final String Driver_Name="Driver_Name";
public static final String Driver_Contact ="Driver_Contact";
public static final String Route_Num ="Route_Num";
public static final String Table_Create="create table" +Table_name+"("+Driver_ID +"integer PRIMARY KEY,"+Driver_Name+" varchar(25),"+Driver_Contact +"integer,"+Route_Num +"integer"+");";
public static final String LOGTAG = null;
public DbHelp(Context context) {
super(context, DB, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
try
{
db.execSQL(Table_Create);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public void addDriver(String name ,String contact,String Route_num) {
db.execSQL("insert into Drivers values(null, '"+name+"' ,"+contact+" , "+ Route_num+" )");
String tag = null;
Log.i(tag, "inserted value");
}
}
main activity code:
package com.example.catchthebus;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
//SqlHelp sql_helper;
//SqlHelp sql_helper1;
//SqlHelp sql2;
SQLiteOpenHelper dbhelp;
SQLiteDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbhelp = new DbHelp(this);
database= dbhelp.getWritableDatabase();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void Open_Passenger_Submit(View view)
{
Intent intt=new Intent(this,Submit_Passenger.class);
startActivity(intt);
//sql_helper.createPassenger();
}
public void Open_Driver_Submit(View view)
{`enter code here`
Intent intt=new Intent(this,Submit_Driver.class);
startActivity(intt);
//sql_helper.createDriver();
}
}
It looks like your Table_Create string was missing some spaces.
public static final String Table_Create="create table " +Table_name+" ("+Driver_ID +" integer PRIMARY KEY,"+Driver_Name+" TEXT,"+Driver_Contact +" integer,"+Route_Num +" integer);";
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;
}
}
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