Database can not be created - java

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!

Related

Sum two numbers in SQL database

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

SQLite create Table not working without any error

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

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

this.getWritableDatabase() causes my Android app to stop [duplicate]

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.

How to view all data from database?

This is my Database helper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="assignment.db";
public static final String TABLE_NAME="assignment_data";
public static final int DATABASE_VERSION=1;
public static final String COL_1="ID";
public static final String COL_2="ASSIGNMENT_NAME";
public static final String COL_3="SUBMISSION_DATE";
public static final String COL_4="INFORMATION";
public static final String COL_5="REMARKS";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String create="create table "+TABLE_NAME+"("+COL_1+" INTEGER PRIMARY KEY AUTOINCREMENT,"+COL_2+" TEXT NOT NULL,"+COL_3+" TEXT NOT NULL,"+COL_4+" TEXT NOT NULL,"+COL_5+" TEXT NOT NULL"+")";
db.execSQL(create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
String upgrade="Drop table if exists "+TABLE_NAME;
db.execSQL(upgrade);
onCreate(db);
}
public boolean addAssignment(Assignment x){
SQLiteDatabase myDB=this.getWritableDatabase();
ContentValues content=new ContentValues();
content.put(COL_2,x.getName());
content.put(COL_3,x.getDate());
content.put(COL_4,x.getInfo());
content.put(COL_5,x.getRemarks());
long result=myDB.insert(TABLE_NAME,null,content);
if(result == -1){
return false;
}
else {
return true;
}
}
public Cursor viewAll(){
SQLiteDatabase MyDB=this.getReadableDatabase();
Cursor res=myDB.rawQuery("SELECT * FROM "+DatabaseHelper.TABLE_NAME,null);
return res;
}
/*public Cursor view(){
Cursor cursor=myDB.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE ID=?",new String[]{COL_1+""});
return cursor;
}*/
}
This is my View class:
public class View extends Activity {
Button viewAll,show;
EditText id;
DatabaseHelper dbHelper;
int id1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
viewAll = (Button)findViewById(R.id.viewAll);
show = (Button)findViewById(R.id.show);
id = (EditText)findViewById(R.id.id);
loadData();
//showData();
}
public void loadData(){
viewAll.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
Cursor cursor = dbHelper.viewAll();
if(cursor.getCount() == 0){
Toast.makeText(getApplicationContext(),"No Data for any Assignment found!",Toast.LENGTH_SHORT).show();
}
StringBuffer s = new StringBuffer("");
while(cursor.moveToNext()){
s.append("ID:"+cursor.getString(0)+"\n");
s.append("ASSIGNMENT NAME:"+cursor.getString(1)+"\n");
s.append("SUBMISSION DATE:"+cursor.getString(2)+"\n");
s.append("INFORMATION:"+cursor.getString(3)+"\n");
s.append("REMARKS:"+cursor.getString(4)+"\n\n");
}
showMessage("ASSIGNMENT DETAILS:",s.toString());
}
});
}
/*public void showData(){
show.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
id1=Integer.parseInt(id.getText().toString());
Cursor m=dbHelper.view(id1);
if(m.getCount()==0){
Toast.makeText(View.this,"No Data for the Assignment found!",Toast.LENGTH_SHORT).show();
}
StringBuffer sb= new StringBuffer();
while(m.moveToNext()){
sb.append("ID:"+m.getString(0)+"\n");
sb.append("ASSIGNMENT NAME:"+m.getString(1)+"\n");
sb.append("SUBMISSION DATE:"+m.getString(2)+"\n");
sb.append("INFORMATION:"+m.getString(3)+"\n");
sb.append("REMARKS:"+m.getString(4)+"\n\n");
}
showMessage("ASSIGNMENT DETAILS:",sb.toString());
}
});
}*/
public void showMessage(String title,String mess){
AlertDialog.Builder x=new AlertDialog.Builder(View.this);
x.setCancelable(true);
x.setTitle(title);
x.setMessage(mess);
x.show();
}
}
And This is the error I get:
07-10 08:51:45.497 27027-27027/com.dutt.rishabh.assignmentbuddy E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dutt.rishabh.assignmentbuddy, PID: 27027
java.lang.NullPointerException
at com.dutt.rishabh.assignmentbuddy.View$1.onClick(View.java:36)
at android.view.View.performClick(View.java:4482)
at android.view.View$PerformClick.run(View.java:18787)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
I don't see your DatabaseHelper instance (dbHelper) getting initialized anywhere.
You need to initialize dbHelper before fetching all the records something like this:
dbHelper = new DatabaseHelper(this);
In your onClick method before entering the while loop add following line:
cursor.moveToFirst();
Then read through the cursor. If this doesn't solve your problem please upload whole LogCat messages
call cursor.moveToPrevious() before while(cursor.moveToNext())

Categories