sqLite Android..Unfortunately, applicaton has stopped - android

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.

Related

I cant call my constructor method SQLite

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.

issue in sqlite app in SQLiteOpenHelper class

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

Trouble in creating database on android using sqlopenhelper

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);";

How to open a database from not database class?

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.

How can I operate SQLite when I use IntentService?

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;
}
}

Categories

Resources