This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 5 years ago.
I am new to Android SQLite database & while executing this.getWritableDatabase() my app stops. Is there any solution to this problem? My database is about getting students' information and saving their marks in the database.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="Dictionary.db";
public static final String TABLE_NAME="Dictionary_data";
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="MARKS";
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 AUTO INCREMENT,NAME TEXT,SURENAME TEXT,MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME);
onCreate(db);
}
public boolean insert_data(String name,String surname,String marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues= new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,marks);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result==-1)
return false;
else
return true;
}
}
And my mainActivity class:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
EditText editName,editSurname,editMark;
Button btn_add_data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this.getApplicationContext());
editName = (EditText)findViewById(R.id.namespace);
editSurname = (EditText)findViewById(R.id.surnamespace);
editMark = (EditText)findViewById(R.id.markspace);
btn_add_data = (Button)findViewById(R.id.add_button);
addData();
}
public void addData(){
btn_add_data.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean id_inserted = myDB.insert_data(editName.getText().toString(),editSurname.getText().toString(),editMark.getText().toString());
if(id_inserted)
Toast.makeText(MainActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not inserted",Toast.LENGTH_LONG).show();
}
}
);
}
}
there is error in create table
db.execSQL("CREATE TABLE"+ TABLE_NAME+ "(ID INTEGER PRIMARY KEY AUTO INCREMENT,NAME TEXT,SURENAME TEXT,MARKS INTEGER)");
please add space after TABLE
db.execSQL("CREATE TABLE "+ TABLE_NAME+ " (ID INTEGER PRIMARY KEY AUTO INCREMENT,NAME TEXT,SURENAME TEXT,MARKS INTEGER)");
also add log cat for more details,i am not able to comment as it's my new account.
Related
I have a program to sum two numbers and save result in SQL then show results in a TextView but I don't know how to make that; help me please.
But this number comes from the user (EditText) or from button ...
must I make a new table for the sum number for example or what .
I watch videos on you tube but I can do it that program.
this my code...
in DataBase activity :
public class DB_sql extends SQLiteOpenHelper {
public static final String name = "data.db";
public static final String TABLE_NAME="mydata";
public static final String KEY_First="first";
public static final String KEY_second="second";
public DB_sql(#Nullable Context context) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table TABLE_NAME ( id INTEGER PRIMARY KEY AUTOINCREMENT, KEY_First INTEGER, KEY_second INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS TABLE_NAME");
onCreate(db);
}
public boolean insertdata (int first,int second){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues numbers = new ContentValues();
numbers.put("first",first);
numbers.put("second",second);
long result = db.insert(TABLE_NAME,null,numbers);
if (result == -1)
return false;
else
return true;
}
in result activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
result = (TextView)findViewById(R.id.result);
int first = getIntent().getIntExtra("number1",0);
int second = getIntent().getIntExtra("number2",0);
Boolean dataSQL = db_sql.insertdata(first,second);
if (dataSQL == true){
Toast.makeText(this,"data inserted",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"data not inserted",Toast.LENGTH_SHORT).show();
}
in MainActivity:
public class MainActivity extends AppCompatActivity {
// DB_sql db_sql = new DB_sql(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void second(View view) {
Intent sec = new Intent(this,result.class);
sec.putExtra("number2",40);
startActivity(sec);
}
public void first(View view) {
Intent fir=new Intent(this,result.class);
fir.putExtra("number1",85);
startActivity(fir);
}
}
Hello as the title says I cannot get the app to construct a small local sqlite database. I would appreciate some help as I m an amateur. Thanks in advance.
Below there are some pictures of my source code.
I tested this code on level 24 API device, but the database does not appear in the data/data/the_package/databases/ folder
Edited to include code
MainActivity.java
public class MainActivity extends AppCompatActivity {
private CrdDBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new CrdDBHelper(this);
boolean p1 = true;
int p11sc = 0;
int p12sc = 0;
Button btnMenu = (Button) findViewById(R.id.btnMenu);
Button btntrue = (Button) findViewById(R.id.btnTrue);
Button btnFalse = (Button) findViewById(R.id.btnFalse);
// All other available code commented out
}
#Override
protected void onDestroy() {
mydb.close();
super.onDestroy();
}
}
CrdDBContract.java
public final class CrdDBContract {
private CrdDBContract(){}
public static final class GameEntry implements BaseColumns {
public static final String TABLE_NAME = "Game";
public static final String COLUMN_KNOWN = "Known";
public static final String COLUMN_TBF = "TBF";
public static final String SQL_CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ _ID + " INTEGER PRIMARY KEY, "
+ COLUMN_KNOWN + " TEXT NOT NULL, "
+ COLUMN_TBF + " TEXT NOT NULL)";
}
}
CrdDBHelper.java
public class CrdDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "CardGame.db";
public static final int DATABASE_VERSION = 1;
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CrdDBContract.GameEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
CrdDBDataInsertion.java
public class CrdDBDataInsertion {
//??????????? Code not available from images
SQLiteDatabase mDB;
private void contentvalues(String Known, String TBF) {
ContentValues values = new ContentValues();
values.put(CrdDBContract.GameEntry.COLUMN_KNOWN,Known);
values.put(CrdDBContract.GameEntry.COLUMN_TBF,TBF);
long newid = mDB.insert(CrdDBContract.GameEntry.TABLE_NAME,null,values);
}
}
Main Activity part1Main Activity part2
Main Activity part3(final)
DB Contract class
DB Helper class
DB insert class part1
DB insert class part2 (final)
You aren't, according to the code, acessing(opening) the database. You are just instantiating the DatabseHelper in MainActivity i.e. mydb = new CrdDBHelper(this);
It is not until an attempt is made to open the database (which is frequently implicit) that the database is actually created.
A simple way would be to force an open when instantiating the database. e.g. call the getWritableDatabase() method in the constructor, like :-
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
getWritableDatabase();
}
Perhaps at that time set an SQLiteDatabase object with the returned SQLiteDatabase, so your Database Helper (CrdDBHelper.java) could be :-
public class CrdDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "CardGame.db";
public static final int DATABASE_VERSION = 1;
SQLiteDatabase mDB;
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mDB = this.getWriteableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CrdDBContract.GameEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
as the onCreate method is called when (and ONLY when) the database is created the Game table will then be created.
I tried to create a database and create one table in it. The database is being created but not the table.it doesn't show any error and also am not able to insert the value into it.I want to create a table and insert the data recieved from the user but the data is not able to add to database, neither it shows any errors.The code is as follows:
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String q = "CREATE TABLE IF NOT EXISTS " + TABLE_NAMETRY + "(" +
COL_ID + " INTEGER PRIMARY KEY, " + COL_NAME + " TEXT, " + COL_PHONE + " TEXT " + ")";`enter code here`
db.execSQL(q);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP table if exist "+TABLE_NAMETRY);
onCreate(db);
}
public boolean insertData(String name,String no)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentvalue = new ContentValues();
contentvalue.put(COL_NAME,name);
contentvalue.put(COL_PHONE,no);
long result = db.insert(TABLE_NAMETRY,null,contentvalue);
if(result==-1)
return false;
else
return true;
}
public class MainActivity extends AppCompatActivity {
DataBaseHelper mydb;
EditText name,no;
Button b1;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb=new DataBaseHelper(this);
name=(EditText)findViewById(R.id.name);
no=(EditText)findViewById(R.id.no);
t1=(TextView)findViewById(R.id.t1);
b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Adding Data", Toast.LENGTH_SHORT).show();
AddData();
}
});
}
public void AddData()
{
boolean check= mydb.insertData(name.getText().toString(),no.getText().toString());
if(check==true)
t1.setText("data submitted");
else
t1.setText("data not submitted");
}
}
Most probably the helper is creating the table (onCreate) and then delete it (onUpgrade).
Here how I create my helper, take notice of the databaseVersion, as it is important when the (onUpgrade) is executed
public class DatabaseOpenHelper extends SQLiteOpenHelper {
private final static String databaseName = "Your_DB_Name";
private final static int databaseVersion = 13;
DatabaseOpenHelper(Context context) {
super(context, databaseName, null, databaseVersion);
}
#Override
public void onCreate(SQLiteDatabase db) { // Do Create Your Table Here }
#Override
public void onUpgrade(SQLiteDatabase db, int Old_Version, int New_Version) { //Delete Your tables here if they exists}
My table is not getting created in Sqlite (Toast for dataNotInserted).Code snippet below...
EXCEPTION
android.database.sqlite.SQLiteException: no such table: PETROL.DB (code 1): , while compiling: INSERT INTO PETROL.DB(AMOUNT) VALUES (?)
Activity2.java
public class Activity2 extends AppCompatActivity {
EditText ET1;
Button B1;
Button Bview;
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
myDb = new DatabaseHelper(this);
ET1 = findViewById(R.id.editText_amount);
B1 = findViewById(R.id.button_add);
Bview = findViewById(R.id.button_view);
AddData();
}
public void AddData() {
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isInserted = myDb.insertData(Integer.parseInt(ET1.getText().toString()));
if (isInserted == true) {
Toast.makeText(Activity2.this, "DataInserted", Toast.LENGTH_LONG).show();
} else
Toast.makeText(Activity2.this, "DataNotInserted", Toast.LENGTH_LONG).show();
}
}
);
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="PETROL.DB";
public static final String TABLE_NAME="PETROL_TABLE";
public static final String COL_1="ID";
public static final String COL_2="AMOUNT";
public DatabaseHelper(Context context)
{
super(context,DATABASE_NAME,null,1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL( "CREATE TABLE " + TABLE_NAME + "(" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_2 + " INTEGER );");
Log.d("data","ghgc");
}
public boolean insertData(int data)
{
SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
ContentValues contextValues=new ContentValues();
contextValues.put("AMOUNT",data);
Log.d("insertData",Integer.toString(data));
long result= sqLiteDatabase.insert(DATABASE_NAME,null,contextValues);
if(result==-1)
return false;//to check if data is inserted
else
return true;
//sqLiteDatabase.close();
}
}
onUpgrade not mentioned since i'm still working on version 1
Your issue is as per the message and is caused as your are passing the Database name PETROL.DB to the insert method instead of passing the table name. As per the method's signature :-
long insert(String table, String nullColumnHack, ContentValues values)
Convenience method for inserting a row into the database. SQLiteDatabase - insert
As such change :-
long result= sqLiteDatabase.insert(DATABASE_NAME,null,contextValues);
to :-
long result= sqLiteDatabase.insert(TABLE_NAME,null,contextValues);
These are the logcat errors which repeat 3 or 4 times when I run the app. I attached the database helper:
Error inserting time_type=3 proto_blob=[B#42439540 sync_state_mod_time_millis=1466838685054 context_id=e7029963-e329-4b1b-bb6e-24bb57e0ba04 end_time=1466837904524 module_id=com.google.android.contextmanager.module.ScreenModule start_time=1466837558811 sync_state=0 context_family=7 context_name=7 version=1
android.database.sqlite.SQLiteConstraintException: column context_id is not unique (code 19)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
at bsv.a(SourceFile:445)
at bsv.b(SourceFile:420)
at bsv.a(SourceFile:370)
at bsv.a(SourceFile:147)
at bsc.a(SourceFile:157)
at bjb.a(SourceFile:64)
at bix.run(SourceFile:52)
at biv.a(SourceFile:258)
at biv.handleMessage(SourceFile:251)
at jcq.run(SourceFile:141)
at jcy.run(SourceFile:438)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at jhi.run(SourceFile:17)
at java.lang.Thread.run(Thread.java:841)
This is the Databasehelper class:
public class databasehelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="USMS.db";
public static final String TABLE_NAME="B_LIST";
public static final String COL1="ID";
public static final String COL2="NAME";
public static final String COL3="NUMBER";
public databasehelper(Context context) {
super(context, DATABASE_NAME, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create Table "+TABLE_NAME+ "(ID INTEGER PRIMARY KEY AUTOINCREMENT, name text, number text);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean InsertData(String name, String number) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values =new ContentValues();
values.put(COL2,name);
values.put(COL3,number);
Long result = db.insert(TABLE_NAME, null ,values);
if(result==-1)
return false;
else
return true;
}
}
and this is my Main Activity class:
public class MainActivity extends AppCompatActivity {
databasehelper myDb;
EditText editname,editnumber;
Button bt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb=new databasehelper(this);
editname = (EditText)findViewById(R.id.editText);
editnumber = (EditText)findViewById(R.id.editText2);
bt1 = (Button) findViewById(R.id.button);
}
public void adddate(){
bt1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
boolean inserted = myDb.InsertData(editname.getText().toString(),editnumber.getText().toString());
if (inserted=true)
Toast.makeText(MainActivity.this,"data inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"not inserted",Toast.LENGTH_LONG).show();
}
});
}
}
I hope someone can help me, thanks in advance!