Android готовая Бд. SQLIte не сохраняет запись
Кнопка должна сохранять запись с EditText-ов в созданную в DB BROWSER FOR SQLite БД, выдает вот такую ошибку:
E/SQLiteLog: (1) near "(": syntax error
E/SQLiteDatabase: Error inserting sleephow=Хорошо time(h)= time(m)= time(s)=1 sleepwake=Да data=05.05.2021 sleepbefore=Играл
android.database.sqlite.SQLiteException: near "(": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO results(sleephow,time(h),time(m),time(s),sleepwake,data,sleepbefore) VALUES (?,?,?,?,?,?,?)
Код DialogFragment,в котором передаю данные с EditText в БД:
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import androidx.fragment.app.DialogFragment;
import com.example.testcalculatedreambd.bd.DatabaseHelper;
public class ResultDialog extends DialogFragment {
SQLiteDatabase db;
Cursor userCursor;
long userId=0;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Создаем интерфейс
View v = inflater.inflate(R.layout.resultdialogs, null);
//Дата
EditText editTextData = v.findViewById(R.id.editTextData);
editTextData.setText(TotalValues.dateText);
//Время
EditText editTextHours = v.findViewById(R.id.editTextHours);
EditText editTextMinutes = v.findViewById(R.id.editTextMinutes);
EditText editTextseconds = v.findViewById(R.id.editTextSeconds);
editTextseconds.setText(Long.toString((TotalValues.elapsedMillslong)/1000));
if (TotalValues.elapsedMillslong > 60000)
editTextMinutes.setText(Long.toString((TotalValues.elapsedMillslong)/60000));
if (TotalValues.elapsedMillslong > 3600000)
editTextHours.setText(Long.toString((TotalValues.elapsedMillslong)/3600000));
//Как спалось
EditText editTextHowSleep = v.findViewById(R.id.editTextHowSleep);
editTextHowSleep.setText(TotalValues.resultDream);
//Просыпался
EditText editTextWakeUp = v.findViewById(R.id.editTextWakeUp);
editTextWakeUp.setText(TotalValues.wakeup);
//Что делал перед сном
EditText editTextBeforeDream = v.findViewById(R.id.editTextBeforeDream);
editTextBeforeDream.setText(TotalValues.thingBeforeDream);
//БД
DatabaseHelper sqlHelper = new DatabaseHelper(getContext());
sqlHelper.create_db();
db = sqlHelper.open();
ContentValues cv = new ContentValues();
Button resultSave = v.findViewById(R.id.resultSave);
resultSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.COLUMN_DATA, editTextData.getText().toString());
cv.put(DatabaseHelper.COLUMN_TIME_SECONDS, editTextseconds.getText().toString());
cv.put(DatabaseHelper.COLUMN_TIME_MINUTES, editTextMinutes.getText().toString());
cv.put(DatabaseHelper.COLUMN_TIME_HOURS, editTextHours.getText().toString());
cv.put(DatabaseHelper.COLUMN_SLEEPHOW, editTextHowSleep.getText().toString());
cv.put(DatabaseHelper.COLUMN_SLEEPWAKE, editTextWakeUp.getText().toString());
cv.put(DatabaseHelper.COLUMN_SLEEPBEFORE, editTextBeforeDream.getText().toString());
if (userId > 0) {
db.update(DatabaseHelper.TABLE, cv, DatabaseHelper.COLUMN_ID + "=" + String.valueOf(userId), null);
} else {
db.insert(DatabaseHelper.TABLE, null, cv);
}
dismiss();
}
});
Button backToBeforeDream = v.findViewById(R.id.backToBeforeDream);
backToBeforeDream.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BeforeDream beforeDream = new BeforeDream();
beforeDream.show(getFragmentManager(), "custom");
dismiss();
}
});
return v;
}
}
Код DatabaseHelper:
package com.example.testcalculatedreambd.bd;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_PATH; // полный путь к базе данных
private static String DB_NAME = "FinalTestBd.db";
private static final int SCHEMA = 1; // версия базы данных
public static final String TABLE = "results"; // название таблицы в бд
// названия столбцов
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DATA = "data";
public static final String COLUMN_TIME_SECONDS = "time(s)";
public static final String COLUMN_TIME_MINUTES = "time(m)";
public static final String COLUMN_TIME_HOURS = "time(h)";
public static final String COLUMN_SLEEPHOW = "sleephow";
public static final String COLUMN_SLEEPWAKE = "sleepwake";
public static final String COLUMN_SLEEPBEFORE= "sleepbefore";
private Context myContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, SCHEMA);
this.myContext=context;
DB_PATH =context.getFilesDir().getPath() + DB_NAME;
}
@Override
public void onCreate(SQLiteDatabase db) { }
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
public void create_db(){
InputStream myInput = null;
OutputStream myOutput = null;
try {
File file = new File(DB_PATH);
if (!file.exists()) {
//получаем локальную бд как поток
myInput = myContext.getAssets().open(DB_NAME);
// Путь к новой бд
String outFileName = DB_PATH;
// Открываем пустую бд
myOutput = new FileOutputStream(outFileName);
// побайтово копируем данные
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
}
}
catch(IOException ex){
Log.d("DatabaseHelper", ex.getMessage());
}
finally {
try{
if(myOutput!=null) myOutput.close();
if(myInput!=null) myInput.close();
}
catch(IOException ex){
Log.d("DatabaseHelper", ex.getMessage());
}
}
}
public SQLiteDatabase open()throws SQLException {
return SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READWRITE);
}
}
Полный лог:
E/SQLiteLog: (1) near "(": syntax error
E/SQLiteDatabase: Error inserting sleephow=Хорошо time(h)= time(m)= time(s)=1 sleepwake=Да data=05.05.2021 sleepbefore=Играл
android.database.sqlite.SQLiteException: near "(": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO results(sleephow,time(h),time(m),time(s),sleepwake,data,sleepbefore) VALUES (?,?,?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:986)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:593)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:61)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:33)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1597)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1468)
at com.example.testcalculatedreambd.ResultDialog$1.onClick(ResultDialog.java:83)
at android.view.View.performClick(View.java:7184)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7161)
at android.view.View.access$3500(View.java:818)
at android.view.View$PerformClick.run(View.java:27677)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)