Related
I would be grateful if anyone could help with this code
android.database.sqlite.SQLiteException: near "WHERE": syntax error (Sqlite code 1): , while compiling: SELECT * FROM WHERE category = 'B', (OS error - 2:No such file or directory)
error from debug
My DbHelper is as following
public class DbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Quiz.db";
private static final String KEY_ID = "id";
private static final String KEY_QUES = "question";
private static final String KEY_ANSWER = "answer"; //correct option
private static final String KEY_OPTA= "opta"; //option a
private static final String KEY_OPTB= "optb"; //option b
private static final String KEY_OPTC= "optc"; //option c
private static final String KEY_OPTD= "optd"; //option d
private static final String KEY_CAT="category"; //category
private static final String TABLE_QUEST1 = "questUnit1";
private SQLiteDatabase dbase;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
public DbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase=db;
String sql1 = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST1 + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_ANSWER+ " TEXT, "+KEY_OPTA +" TEXT, "
+KEY_OPTB +" TEXT, "+KEY_OPTC+" TEXT, "+KEY_OPTD+" TEXT, "+KEY_CAT+" TEXT)";
db.execSQL(sql1);
addQuestionsUnit1();
}
private void addQuestionsUnit1() {
QuestionUnit1 q101 = new QuestionUnit1("What is the decimal equivalent of the binary number 10111","21","23","39","42","23","B");
this.addQuestionsUnit1(q101);
QuestionUnit1 q102 = new QuestionUnit1("In order to write on a floppy disk with your IBM PC, you must first","digitize it","format it","compile it","hardware it","format it","B");
this.addQuestionsUnit1(q102);
QuestionUnit1 q249= new QuestionUnit1("Firewalls are used to protect against","Unauthorized Attacks","Viruses","Fire Attacks","Data Driven Attacks","Unauthorized Attacks","E");
this.addQuestionsUnit1(q249);
QuestionUnit1 q250= new QuestionUnit1("The first Digital Computer introduced, was named as ","UNIVAC","EDSAC","ENIAC","MARK-1","MARK-1","E");
this.addQuestionsUnit1(q250);
}
public void addQuestionsUnit1(QuestionUnit1 quest) {
//SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION1());
values.put(KEY_ANSWER, quest.getANSWER1());
values.put(KEY_OPTA, quest.getOPTA1());
values.put(KEY_OPTB, quest.getOPTB1());
values.put(KEY_OPTC, quest.getOPTC1());
values.put(KEY_OPTD, quest.getOPTD1());
values.put(KEY_CAT,quest.getCATEGORY1());
// Inserting Row
dbase.insert(TABLE_QUEST1, null, values);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public List<QuestionUnit1> getAllQuestions1(String tname, String lname)
{
List<QuestionUnit1> quesList1 = new ArrayList<QuestionUnit1>();
String selectQuery1 = "SELECT * FROM " + tname+" WHERE "+KEY_CAT+" = '"+lname+"'";
dbase=this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery1, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
QuestionUnit1 quest1 = new QuestionUnit1();
quest1.setID1(cursor.getInt(0));
quest1.setQUESTION1(cursor.getString(1));
quest1.setANSWER1(cursor.getString(2));
quest1.setOPTA1(cursor.getString(3));
quest1.setOPTB1(cursor.getString(4));
quest1.setOPTC1(cursor.getString(5));
quest1.setOPTD1(cursor.getString(6));
quesList1.add(quest1);
} while (cursor.moveToNext());
}
return quesList1;
}// end pubic list
}
the code walks like that a butto to To Exercise Activity
if(position == 2){
Intent i= new Intent(getApplicationContext(),Unit1ExerciseActivity.class);
i.putExtra("table_name",tableName);
i.putExtra("level_name","B");
startActivity(i);
overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
}
and the code in the exercise Activity is
public class Unit1ExerciseActivity extends AppCompatActivity {
List<QuestionUnit1> quesList1;
public int score=0;
int ctr1=1;
QuestionUnit1 currentQ1;
TextView txtQuestion1;
RadioGroup grp;
RadioButton rda1, rdb1, rdc1, rdd1;
Button butNext1;
Random random1 = new Random();
ArrayList<Integer> list = new ArrayList<Integer>();
TextView textViewTime1;
public ArrayList<String> wrongQuestListUnit1 = new ArrayList<String>();
public ArrayList<String> selectedAnsUnit1 = new ArrayList<String>();
public ArrayList<String> actualAnswerUnit1 = new ArrayList<String>();
int number;
ProgressBar progressBar;
int progress = 1;
String tableName="",catName="";
TextView qstnNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.unit1_exercise_activity);
qstnNo = (TextView)findViewById(R.id.qstnNo);
Intent iin=getIntent();
Bundle b=iin.getExtras();
if(b!=null){
tableName=(String)b.get("table_name");
catName=(String)b.get("level_name");
Log.d("Table Name",tableName);
Log.d("Level Name",catName);
}
number=0;
DbHelper db= new DbHelper(this);
textViewTime1 = (TextView)findViewById(R.id.textViewTime);
final CounterClass timer = new CounterClass(1800000, 1000);
timer.start();
quesList1=db.getAllQuestions1(tableName,catName);
for(int i=0;i<50;i++){
while(true){
int next = random1.nextInt(50);
if(!list.contains(next))
{
list.add(next);
break;
}
}
}
currentQ1=quesList1.get(list.get(0));
txtQuestion1=(TextView)findViewById(R.id.textView1);
rda1=(RadioButton)findViewById(R.id.radio0);
rdb1=(RadioButton)findViewById(R.id.radio1);
rdc1=(RadioButton)findViewById(R.id.radio2);
rdd1=(RadioButton)findViewById(R.id.radio3);
butNext1=(Button)findViewById(R.id.button1);
setQuestionView();
grp = (RadioGroup) findViewById(R.id.radioGroup1);
butNext1.setEnabled(false);
grp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if(i== R.id.radio0 || i == R.id.radio1 || i==R.id.radio2 || i == R.id.radio3)
butNext1.setEnabled(true);
}
});
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(30);
progressBar.setProgress(1);
butNext1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progress = progress+1;
progressBar.setProgress(progress);
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
//Log.d("yourans", currentQ1.getANSWER1() + " " + answer.getText());
if (currentQ1.getANSWER1().equals(answer.getText())) {
score++;
//Log.d("score", "Your score" + score1);
}
else
{
wrongQuestListUnit1.add(number, currentQ1.getQUESTION1());
selectedAnsUnit1.add(number, answer.getText().toString());
actualAnswerUnit1.add(number, currentQ1.getANSWER1());
number++;
}
grp.clearCheck();
butNext1.setEnabled(false);
if (ctr1 < 31) {
if (ctr1 == 30) {
butNext1.setText("End Test");
}
currentQ1 = quesList1.get(list.get(ctr1));
setQuestionView();
} else {
timer.onFinish();
timer.cancel();
}
}
});
}
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
textViewTime1.setText(hms);
}
#Override
public void onFinish() {
showResult();
}
}
public void showResult(){
Intent intent = new Intent(Unit1ExerciseActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("scoreUnit1 ", score);//Your score
b.putString("section",tableName);//Your table name
b.putString("category",catName);//Your category name
intent.putStringArrayListExtra("wrongQuestions", wrongQuestListUnit1);
intent.putStringArrayListExtra("selectedAnswer", selectedAnsUnit1);
intent.putStringArrayListExtra("actualAnswer", actualAnswerUnit1);
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
private void setQuestionView(){
txtQuestion1.setText(currentQ1.getQUESTION1());
rda1.setText(currentQ1.getOPTA1());
rdb1.setText(currentQ1.getOPTB1());
rdc1.setText(currentQ1.getOPTC1());
rdd1.setText(currentQ1.getOPTD1());
if(ctr1<10)
qstnNo.setText("0" + ctr1 + "/30");
else
qstnNo.setText("" + ctr1+ "/30");
ctr1++;
}
#Override
public void onBackPressed() {
//super.onBackPressed();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Uncomment the below code to Set the message and title from the strings.xml file
//builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
//Setting message manually and performing action on button click
builder.setMessage("If you close all your progress would not be saved... Do you wish to exit ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
//Creating dialog box
AlertDialog alert = builder.create();
//Setting the title manually
// alert.setTitle("CompQuiz");
alert.show();
}
}
You are probably passing/getting a null tableName.
Try this:
if(b!=null){
tableName=b.getString("table_name");
catName=b.getString("level_name");
Log.d("Table Name",tableName);
Log.d("Level Name",catName);
}
Try this please:
public void addQuestionsUnit1(QuestionUnit1 quest){
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(KEY_QUES, quest.getQUESTION1());
values.put(KEY_ANSWER, quest.getANSWER1());
values.put(KEY_OPTA, quest.getOPTA1());
values.put(KEY_OPTB, quest.getOPTB1());
values.put(KEY_OPTC, quest.getOPTC1());
values.put(KEY_OPTD, quest.getOPTD1());
values.put(KEY_CAT,quest.getCATEGORY1());
// Inserting Row
dbase.insert(TABLE_QUEST1, null, values);
db.setTransactionSuccessful();
} catch (Exception e) {
Log.d("DB insertion", "Error while trying to add values to database");
} finally {
db.endTransaction();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public List<QuestionUnit1> getAllQuestions1(String tname, String lname)
{
List<QuestionUnit1> quesList1 = new ArrayList<QuestionUnit1>();
String selectQuery1 = "SELECT * FROM " + tname+" WHERE "+KEY_CAT+" = '"+lname+"'";
dbase= getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery1, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
QuestionUnit1 quest1 = new QuestionUnit1();
quest1.setID1(cursor.getInt(0));
quest1.setQUESTION1(cursor.getString(1));
quest1.setANSWER1(cursor.getString(2));
quest1.setOPTA1(cursor.getString(3));
quest1.setOPTB1(cursor.getString(4));
quest1.setOPTC1(cursor.getString(5));
quest1.setOPTD1(cursor.getString(6));
quesList1.add(quest1);
} while (cursor.moveToNext());
}
cursor.close();
return quesList1;
}
}
I do not know why I can't add boolean insertData = dbHelper.addData(emailString, nameString,ageString, preferencesString,passwordString) where the addData keep showing error in the lines of code provided below. I wanted to add the if-else statement there is because I wanted it to make sure during the insert data process, a user has to fill in all the details in order to create an account, but not leaving blanks on any of the fields given for them to fill in. or I need to do it in another way? I'm still a newbie for android studio. Please help me.
private void getData() {
name = "" + Pname.getText().toString().trim();
age = "" + PAge.getText().toString().trim();
phone = "" + Pphone.getText().toString().trim();
preferenceselected = "" + Ppreferenceselected.getText().toString().trim();
String timeStamp = "" + System.currentTimeMillis();
long id = dbHelper.insertInfo(
"" + imageUri,
"" + name,
"" + age,
"" + phone,
"" + preferenceselected,
"" + timeStamp,
"" + timeStamp
);
String emailString = Pemail.getText().toString();
String nameString = Pname.getText().toString();
String ageString = PAge.getText().toString();
String preferencesString = Ppreferenceselected.getText().toString();
String passwordString = Ppassword.getText().toString();
boolean insertData = dbHelper.addData(emailString, nameString,ageString, preferencesString,passwordString);
if (insertData == true) {
Toast.makeText(MainActivity.this, "Account Created", Toast.LENGTH_LONG).show();
Intent goappsetting = new Intent(MainActivity.this,setting.class);
startActivity(goappsetting);
}else {
Toast.makeText(MainActivity.this, "Please do not leave any blanks or user exist", Toast.LENGTH_LONG).show();
}
Toast.makeText(this, "Account Created", Toast.LENGTH_SHORT).show();
}
this is my MainActivity.Java
public class MainActivity extends AppCompatActivity {
private DatabaseHelper dbHelper;
private ImageView pImageView;
private EditText Pemail, Pname, PAge, Pphone, Ppassword;
private TextView loginacclink, Ppreferenceselected;
Button createacc, preferencebtn;
ActionBar actionBar;
String[] categories;
boolean[] checkeditems;
ArrayList<Integer> mUserItems = new ArrayList<>();
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 101;
private static final int IMAGE_PICK_CAMERA_CODE = 102;
private static final int IMAGE_PICK_GALLERY_CODE = 103;
private String[] cameraPermissions;
private String[] storagePermissions;
private Uri imageUri;
private String name, age, phone;
private String preferenceselected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// this is the status bar
actionBar = getSupportActionBar();
actionBar.setTitle("Create Account");
// this is for the check list
categories = getResources().getStringArray(R.array.user_categories);
checkeditems = new boolean[categories.length];
// this is for the items in the xml file
pImageView = findViewById(R.id.personImage);
Pemail = findViewById(R.id.email);
Pname = findViewById(R.id.name);
PAge = findViewById(R.id.age);
Pphone = findViewById(R.id.phone);
Ppassword = findViewById(R.id.password);
createacc = findViewById(R.id.createacc);
preferencebtn = findViewById(R.id.preferencebtn);
loginacclink = findViewById(R.id.loginacclink);
Ppreferenceselected = (TextView) findViewById(R.id.preferenceselected);
dbHelper = new DatabaseHelper(this);
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
pImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imagePickDialog();
}
});
preferencebtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setTitle(R.string.dialog_title);
mBuilder.setMultiChoiceItems(categories, checkeditems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int position, boolean isChecked) {
if (isChecked) {
if (!mUserItems.contains(position)) {
mUserItems.add(position);
}
} else if (mUserItems.contains(position)) {
mUserItems.remove(position);
}
}
});
mBuilder.setCancelable(false);
mBuilder.setPositiveButton(R.string.ok_label, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
String item = "";
for (int i = 0; i < mUserItems.size(); i++) {
item = item + categories[mUserItems.get(i)];
if (i != mUserItems.size() - 1) {
item = item + ",";
}
}
Ppreferenceselected.setText(item);
}
});
mBuilder.setNegativeButton(R.string.dismiss_label, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
mBuilder.setNeutralButton(R.string.clear_all_label, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
for (int i = 0; i < checkeditems.length; i++) {
checkeditems[i] = false;
mUserItems.clear();
Ppreferenceselected.setText("");
}
}
});
AlertDialog mDialog = mBuilder.create();
mDialog.show();
}
});
loginacclink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, login.class);
startActivity(intent); }
});
createacc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// insert data into db
getData();
}
});
}
private void getData() {
name = "" + Pname.getText().toString().trim();
age = "" + PAge.getText().toString().trim();
phone = "" + Pphone.getText().toString().trim();
preferenceselected = "" + Ppreferenceselected.getText().toString().trim();
String timeStamp = "" + System.currentTimeMillis();
long id = dbHelper.insertInfo(
"" + imageUri,
"" + name,
"" + age,
"" + phone,
"" + preferenceselected,
"" + timeStamp,
"" + timeStamp
);
String emailString = Pemail.getText().toString();
String nameString = Pname.getText().toString();
String ageString = PAge.getText().toString();
String preferencesString = Ppreferenceselected.getText().toString();
String passwordString = Ppassword.getText().toString();
boolean insertData = dbHelper.addData(emailString, nameString,ageString, preferencesString,passwordString);
if (insertData == true) {
Toast.makeText(MainActivity.this, "Account Created", Toast.LENGTH_LONG).show();
Intent goappsetting = new Intent(MainActivity.this,setting.class);
startActivity(goappsetting);
}else {
Toast.makeText(MainActivity.this, "Please do not leave any blanks or user exist", Toast.LENGTH_LONG).show();
}
Toast.makeText(this, "Account Created", Toast.LENGTH_SHORT).show();
}
private void imagePickDialog() {
String[] options = {"Camera", "Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick Image From");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
if (!checkCameraPermission()) {
requestCameraPermission();
}
else {
pickFromCamera();
}
}
else if (which == 1) {
if (!checkStoragePermission()) {
requestStoragePermission();
}
else {
pickFromGallery();
}
}
}
});
builder.create().show();
}
private boolean checkCameraPermission() {
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission() {
ActivityCompat.requestPermissions(this, cameraPermissions, CAMERA_REQUEST_CODE);
}
private void pickFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
private void pickFromCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Image title");
values.put(MediaStore.Images.Media.DESCRIPTION, "Image description");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
private boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestStoragePermission() {
ActivityCompat.requestPermissions(this, storagePermissions, STORAGE_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CAMERA_REQUEST_CODE: {
if (grantResults.length>0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && storageAccepted) {
pickFromCamera();
}
else {
Toast.makeText(this, "Camera permission required!", Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE:{
if (grantResults.length>0) {
boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (storageAccepted) {
pickFromGallery();
}
else {
Toast.makeText(this, "Storage permission required!", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
CropImage.activity(data.getData())
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
else if (requestCode == IMAGE_PICK_CAMERA_CODE) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
imageUri = resultUri;
pImageView.setImageURI(resultUri);
}
else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Toast.makeText(this, ""+error, Toast.LENGTH_SHORT).show();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
This is my DatabaseHelper.Java
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(#Nullable Context context) {
super(context, constants.DB_NAME, null, constants.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(constants.CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + constants.TABLE_NAME);
onCreate(db);
}
public long insertInfo(String image, String name, String age, String phone, String preference, String addTimeStamp, String updateTimeStamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(constants.C_NAME, name);
values.put(constants.C_AGE, age);
values.put(constants.C_PHONE, phone);
values.put(constants.C_PREFERENCES, preference);
values.put(constants.C_IMAGE, image);
values.put(constants.C_Add_TIMESTAMP, addTimeStamp);
values.put(constants.C_UPDATED_TIMESTAMP, updateTimeStamp);
long id = db.insert(constants.TABLE_NAME, null, values);
db.close();
return id;
}
}
This is constance.Java
public class constants {
public static final String DB_NAME = "MMTA_DB";
public static final int DB_VERSION = 1;
public static final String TABLE_NAME = "USER_TABLE";
public static final String C_EMAIL = "EMAIL";
public static final String C_NAME = "NAME";
public static final String C_AGE = "AGE";
public static final String C_PHONE = "PHONE";
public static final String C_PASSWORD = "PASSWORD";
public static final String C_PREFERENCES = "PREFERENCES";
public static final String C_IMAGE = "IMAGE";
public static final String C_Add_TIMESTAMP = "TIMESTAMP";
public static final String C_UPDATED_TIMESTAMP = "UPDATED_TIMESTAMP";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ("
+ C_EMAIL + " TEXT PRIMARY KEY ,"
+ C_NAME + " TEXT,"
+ C_AGE + " TEXT,"
+ C_PHONE + " TEXT,"
+ C_PASSWORD + " TEXT,"
+ C_PREFERENCES + " TEXT,"
+ C_IMAGE + " TEXT,"
+ C_Add_TIMESTAMP + " TEXT,"
+ C_UPDATED_TIMESTAMP + " TEXT"
+ ");";
}
The method addData(String,String,String,String,String) is missing from DatabaseHelper class. Please add this method in that class.
Update the DatabaseHelper class.
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(#Nullable Context context) {
super(context, constants.DB_NAME, null, constants.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(constants.CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + constants.TABLE_NAME);
onCreate(db);
}
public long insertInfo(String image, String name, String age, String phone, String preference, String addTimeStamp, String updateTimeStamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(constants.C_NAME, name);
values.put(constants.C_AGE, age);
values.put(constants.C_PHONE, phone);
values.put(constants.C_PREFERENCES, preference);
values.put(constants.C_IMAGE, image);
values.put(constants.C_Add_TIMESTAMP, addTimeStamp);
values.put(constants.C_UPDATED_TIMESTAMP, updateTimeStamp);
long id = db.insert(constants.TABLE_NAME, null, values);
db.close();
return id;
}
//add the method
public boolean addData(String parameter1,String parameter2,String parameter3,String parameter4,String parameter5) {
// put here your logic
return false;
}
}
I have a problem with creating two tables in sqlite and display them in RecyclerView and more specifically with one table. I add to the question a screenshot of the application so that you can understand what the problem is.
I have 3 activities: FirstActivity, in which there are two buttons (Monday and Tuesday) -> from this activity we go to MainActivity, on the button selection (Monday) -> save data in table_MON and after selection button (Tuesday) in the table_Tue. The problem is that everything works correctly, when we press the button (Monday) we can save the training, edit and delete it. However, when we go to the button (Tuesday) we can only add training, but we can't edit or delete them. However, I have no idea why? I am already looking at this problem for a week and I have no idea what is going on, maybe a fresh look will help solve the problem.
My database consists of two tables: tableMon and tableTue, but I use the same columns in it (exercises, weight etc ..), and separate _id, and I do not know if this can be a problem. Perhaps the problem is that I use MainActivity in both cases?
Screenshot App:
FirstActivity
enter image description here
Click button Monday --> MainActivity.class
enter image description here
Click button Tuesday --> MainActivity.class
enter image description here
Button Tuesday --> DetailActivity and her is the problem I can't update and delete training.
enter image description here
FirstActivity.class
public class FirstActivity extends AppCompatActivity {
Button buttonMon, buttonTue;
public static final String BUTTON_KEY1 = "BUTTON_KEY";
public static final String BUTTON_KEY2 = "BUTTON_KEY2";
public static final String BUTTON_VALUE = "1";
public static final String BUTTON_VALUE2 = "2";
public static boolean WAS_RUNNING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
buttonMon = (Button) findViewById(R.id.buttonMonday);
buttonTue = (Button) findViewById(R.id.buttonTuesday);
WAS_RUNNING = false;
//OPEN THE SAME MAINACTIVITY
buttonMon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WAS_RUNNING = true;
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
intent.putExtra(BUTTON_KEY1, BUTTON_VALUE);
startActivity(intent);
} });
//OPEN THE SAME MAINACTIVITY
buttonTue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WAS_RUNNING = true;
Intent i = new Intent(FirstActivity.this, MainActivity.class);
i.putExtra(BUTTON_KEY2, BUTTON_VALUE2);
startActivity(i);
} });}}
MainActivity.class
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MyAdapter myAdapter;
private ArrayList<Training> trainingArrayList = new ArrayList<Training>();
private EditText editTextExercise, editTextWeight, editTextRepeat, editTextSeries;
private Button buttonSave, buttonBack;
private Dialog dialog;
private String value;
private String value2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = getIntent().getExtras();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();}});
if(bundle == null)
{return;}
value = bundle.getString(FirstActivity.BUTTON_KEY1);
value2 = bundle.getString(FirstActivity.BUTTON_KEY2);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
if(value != null) {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
myAdapter = new MyAdapter(this, trainingArrayList);
//Refresh MON TABLE
refreshMonTable();
}else if(value2 != null) {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
myAdapter = new MyAdapter(this, trainingArrayList);
//Refresh TUE TABLE
refreshTueTable(); }}
public void showDialog()
{
dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_layout);
editTextExercise = (EditText) dialog.findViewById(editTextExerciseDialog);
editTextWeight = (EditText) dialog.findViewById(editTextWeightDialog);
editTextRepeat = (EditText) dialog.findViewById(editTextRepeatDialog);
editTextSeries = (EditText) dialog.findViewById(editTextSeriesDialog);
buttonSave = (Button) dialog.findViewById(buttonSaveDialog);
buttonBack = (Button) dialog.findViewById(buttonBackDialog);
buttonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();}});
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(value != null) {
saveDataMon(editTextExercise.getText().toString(),
String.valueOf(editTextWeight.getText().toString()),
String.valueOf(editTextRepeat.getText().toString()),
String.valueOf(editTextSeries.getText().toString()));
} else if(value2 != null) {
saveDataTue(editTextExercise.getText().toString(),
String.valueOf(editTextWeight.getText().toString()),
String.valueOf(editTextRepeat.getText().toString()),
String.valueOf(editTextSeries.getText().toString()));
}}});
dialog.show();}
private void saveDataMon(String exercise, String weight, String repeat, String series)
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
long result = adapter.addMon(exercise, weight, repeat, series);
if (result > 0) {
editTextExercise.setText("");
editTextWeight.setText("");
editTextRepeat.setText("");
editTextSeries.setText("");
dialog.dismiss();
} else {
Snackbar.make(editTextExercise, "Unable to save!", Snackbar.LENGTH_SHORT).show();}
adapter.closeDB();
refreshMonTable();}
private void saveDataTue(String exercise, String weight, String repeat, String series)
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
long result = adapter.addTue(exercise, weight, repeat, series);
if (result > 0) {
editTextExercise.setText("");
editTextWeight.setText("");
editTextRepeat.setText("");
editTextSeries.setText("");
dialog.dismiss();
} else {
Snackbar.make(editTextExercise, "Unable to save!", Snackbar.LENGTH_SHORT).show();
}
adapter.closeDB();
refreshTueTable();}
private void refreshMonTable()
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
trainingArrayList.clear();
Cursor cursor = adapter.getAllTreningMon();
if(cursor != null)
{ if(cursor.moveToFirst())
{
do {
int id = cursor.getInt(0);
String cwiczenie = cursor.getString(1);
String ciezar = cursor.getString(2);
String powtorzenia = cursor.getString(3);
String serie = cursor.getString(4);
Training training = new Training(id, cwiczenie, ciezar, powtorzenia, serie);
trainingArrayList.add(training);
}while (cursor.moveToNext());}}
recyclerView.setAdapter(myAdapter);
adapter.closeDB(); }
private void refreshTueTable()
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
trainingArrayList.clear();
Cursor cursor = adapter.getAllTreningTue();
if(cursor != null)
{ if(cursor.moveToFirst())
{
do {
int id = cursor.getInt(0);
String exercise = cursor.getString(1);
String weight = cursor.getString(2);
String repeat = cursor.getString(3);
String series = cursor.getString(4);
Training training = new Training(id, exercise, weight, repeat, series);
trainingArrayList.add(training);
}while (cursor.moveToNext());}}
recyclerView.setAdapter(myAdapter);
adapter.closeDB();
}
#Override
protected void onResume() {
super.onResume();
if(value != null) {
//REFRESH
refreshMonTable();
} else if(value2 != null) {
refreshTueTable();}}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Exit?")
.setMessage("Do you want to exit?")
.setNegativeButton("No", null)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.super.onBackPressed();
}
}).create().show();}}
DetailActivity.class
public class DetailActivity extends AppCompatActivity {
private EditText editTextExerciseDetail, editTextWeightDetail, editTextRepeatDetail, editTextSeriesDetail;
private Button buttonUpdate;
private Button buttonDelete;
String mon;
String tue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Bundle intent = getIntent().getExtras();
if(intent == null)
{return;}
mon = intent.getString(MyAdapter.KEY_MON);
tue = intent.getString(MyAdapter.KEY_TUE);
final int idT = intent.getInt("id");
String cwiczenie = intent.getString("exercise");
String ciezar = intent.getString("weight");
String powtorzenia = intent.getString("repeat");
String serie = intent.getString("series");
editTextExerciseDetail = (EditText) findViewById(R.id.exerciseEditTxtDetail);
editTextWeightDetail = (EditText) findViewById(R.id.weightEditTextDetail);
editTextRepeatDetail = (EditText) findViewById(R.id.repeatEditTextDetail);
editTextSeriesDetail = (EditText) findViewById(R.id.seriesEditTextDetail);
buttonUpdate = (Button) findViewById(R.id.updateBtn);
buttonDelete = (Button) findViewById(R.id.deleteBtn);
editTextExerciseDetail.setText(cwiczenie);
editTextWeightDetail.setText(ciezar);
editTextRepeatDetail.setText(powtorzenia);
editTextSeriesDetail.setText(serie);
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mon != null) {
updateMon(idT, editTextExerciseDetail.getText().toString(),
editTextWeightDetail.getText().toString(),
editTextRepeatDetail.getText().toString(),
editTextSeriesDetail.getText().toString());
} else if(tue != null) {
updateTue(idT, editTextExerciseDetail.getText().toString(),
editTextWeightDetail.getText().toString(),
editTextRepeatDetail.getText().toString(),
editTextSeriesDetail.getText().toString());}}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(DetailActivity.this);
builder.setMessage("Do you want delete this training?")
.setTitle("Delete")
.create();
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(mon != null) {
deleteMon(idT);
}else if(tue != null){
deleteTue(idT);}}});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}});
builder.show();}});}
//Update MON TABLE
private void updateMon(int id, String newExercise, String newWeight, String newRepeat, String newSeries)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.updateMon(id, newExercise, newWeight, newRepeat, newSeries);
if(result > 0)
{
editTextExerciseDetail.setText(newExercise);
editTextWeightDetail.setText(newWeight);
editTextRepeatDetail.setText(newRepeat);
editTextSeriesDetail.setText(newSeries);
this.finish();
Snackbar.make(editTextExerciseDetail, "Updated Succesfully", Snackbar.LENGTH_SHORT).show();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to updated", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();
}
//Update TUE TABLE
private void updateTue(int id, String newExercise, String newWeight, String newRepeat, String newSeries)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.updateTue(id, newExercise, newWeight, newRepeat, newSeries);
if(result > 0)
{
editTextExerciseDetail.setText(newExercise);
editTextWeightDetail.setText(newWeight);
editTextRepeatDetail.setText(newRepeat);
editTextSeriesDetail.setText(newSeries);
this.finish();
Snackbar.make(editTextExerciseDetail, "Updated Succesfully", Snackbar.LENGTH_SHORT).show();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to updated", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();}
//DELETE MON TABLE
private void deleteMon(int id)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.deleteMon(id);
if(result>0)
{
this.finish();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to deleted", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();
}
//DELETE TUE TABLE
private void deleteTue(int id)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.deleteTue(id);
if(result>0)
{
this.finish();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to deleted", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();}
#Override
protected void onResume() {
super.onResume();}
#Override
protected void onRestart() {
super.onRestart();}}
DBHelper.class
public class DBHelper extends SQLiteOpenHelper {
//DB
static final String DB_NAME = "training_db";
static final int DB_VERSION = '1';
//TABLES
static final String TB_NAME_MON = "training_tb_mon";
static final String TB_NAME_TUE = "training_tb_tue";
//COLUMNS
static final String ROW_ID_MON = "id_Mon";
static final String ROW_ID_TUE = "id_Tue";
//ROW
static final String EXERCISE = "exercise";
static final String WEIGHT = "weight";
static final String REPEAT = "repeat";
static final String SERIES = "series";
static final String CREATE_TB_MON = "CREATE TABLE training_tb_mon (id_Mon INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "exercise TEXT NOT NULL, weight TEXT NOT NULL, repeat TEXT NOT NULL, series TEXT NOT NULL);";
static final String CREATE_TB_TUE = "CREATE TABLE training_tb_tue (id_Tue INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "exercise TEXT NOT NULL, weight TEXT NOT NULL, repeat TEXT NOT NULL, series TEXT NOT NULL);";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TB_MON);
db.execSQL(CREATE_TB_TUE);
}catch (Exception e) {
e.printStackTrace();
}}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TB_NAME_MON);
db.execSQL("DROP TABLE IF EXISTS " + TB_NAME_TUE);
onCreate(db);
}}
DBAdapter.class
public class DBAdapter {
Context c;
DBHelper dbHelper;
SQLiteDatabase db;
public DBAdapter(Context c) {
this.c = c;
dbHelper = new DBHelper(c);
}
//OPEN DATABASE
public DBAdapter openDatabase() {
try {
db = dbHelper.getWritableDatabase();
}catch (SQLiteException e) {
e.printStackTrace();
}
return this;
}
//CLOSE DATABASE
public void closeDB()
{
try{
dbHelper.close();
}catch (SQLiteException e){
e.printStackTrace();
}}
//Add training Mon
public long addMon(String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
return db.insert(DBHelper.TB_NAME_MON, DBHelper.ROW_ID_MON, contentValues);
}catch (SQLiteException e) {
e.printStackTrace(); }
return 0;}
//Add training Tue
public long addTue(String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
return db.insert(DBHelper.TB_NAME_TUE, DBHelper.ROW_ID_TUE, contentValues);
}catch (SQLiteException e) {
e.printStackTrace();
}
return 0;
}
//REFRESH TABLE MON
public long updateMon(int id, String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
contentValues.put(DBHelper.ROW_ID_MON, id);
return db.update(DBHelper.TB_NAME_MON, contentValues, DBHelper.ROW_ID_MON + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace(); }
return 0;
}
//REFRESH TABLE TUE
public long updateTue(int id, String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
contentValues.put(DBHelper.ROW_ID_TUE, id);
return db.update(DBHelper.TB_NAME_TUE, contentValues, DBHelper.ROW_ID_TUE + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace();
}
return 0;
}
//DELETE ROW TABLE MON
public long deleteMon(int id)
{
try{
return db.delete(DBHelper.TB_NAME_MON, DBHelper.ROW_ID_MON + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace();
}
return 0; }
//DELETE ROW TABLE TUE
public long deleteTue(int id)
{
try{
return db.delete(DBHelper.TB_NAME_TUE, DBHelper.ROW_ID_TUE + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace();}
return 0;}
//ALL TRAINING TABLE MON
public Cursor getAllTreningMon() {
try{
String[] columns = {DBHelper.ROW_ID_MON, DBHelper.EXERCISE, DBHelper.WEIGHT, DBHelper.REPEAT, DBHelper.SERIES};
return db.query(DBHelper.TB_NAME_MON, columns, null, null, null, null, null);
}catch (SQLiteException e)
{
e.printStackTrace();
}
return null;
}
//ALL TRAINING TABLE TUE
public Cursor getAllTreningTue() {
try{
String[] columns = {DBHelper.ROW_ID_TUE, DBHelper.EXERCISE, DBHelper.WEIGHT, DBHelper.REPEAT, DBHelper.SERIES};
return db.query(DBHelper.TB_NAME_TUE, columns, null, null, null, null, null);
}catch (SQLiteException e)
{
e.printStackTrace();
}
return null;}}
MyAdapter.class
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
ArrayList<Training> training;
public static String KEY_MON = "KEY_MON";
public static String KEY_TUE = "KEY_TUE";
public static String VALUE_MON = "10";
public static String VALUE_TUE = "20";
public <T extends Training> MyAdapter(Context c, ArrayList<Training> training) {
this.c = c;
this.training = training;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(c).inflate(R.layout.card_view_model, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
holder.textViewModel.setText(training.get(position).getExercise());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v) {
if (FirstActivity.WAS_RUNNING)
{Intent intent = new Intent(c, DetailActivity.class);
intent.putExtra(KEY_MON, VALUE_MON);
intent.putExtra("id", training.get(position).getId());
intent.putExtra("exercise", training.get(position).getExercise());
intent.putExtra("weight", training.get(position).getWeight());
intent.putExtra("repeat", training.get(position).getRepeat());
intent.putExtra("series", training.get(position).getSeries());
c.startActivity(intent);
} else if (FirstActivity.WAS_RUNNING)
{Intent intent2 = new Intent(c, DetailActivity.class);
intent2.putExtra(KEY_TUE, VALUE_TUE);
intent2.putExtra("id", training.get(position).getId());
intent2.putExtra("exercise", training.get(position).getExercise());
intent2.putExtra("weight", training.get(position).getWeight());
intent2.putExtra("repeat", training.get(position).getRepeat());
intent2.putExtra("series", training.get(position).getSeries());
c.startActivity(intent2);
}}});}
#Override
public int getItemCount() {
return training.size();}}
Training.class
public class Training {
int id;
String exercise;
String weight;
String repeat;
String series;
public Training(int id, String exercise, String weight, String repeat, String series) {
this.id = id;
this.exercise = exercise;
this.weight = weight;
this.repeat = repeat;
this.series = series;
}
public int getId() {return id;}
public void setId(int id) { this.id = id;}
public String getExercise() {return exercise; }
public void setExercise(String exercise) {this.exercise = exercise;}
public String getWeight() {return weight;}
public void setWeight(String weight) {this.weight = weight; }
public String getRepeat() {return repeat;}
public void setRepeat(String repeat) { this.repeat = repeat;}
public String getSeries() {return series;}
public void setSeries(String series) {this.series = series;}}
In your MyAdapter class, in the onItemClick method, within the onBindViewHolder method, the second check, for Tue processing, would never run.
You have :-
if (FirstActivity.WAS_RUNNING) {
.......
} else if (FirstActivity.WAS_RUNNING) {
.......
}
i.e. you are saying if FirstActivity was not running and the FirstActivity was running then do your stuff.
i.e. the else will only be entered if FirstActivity were not running, in which case the if (FirstActivity.WAS_RUNNING) would never be true.
Perhaps have 2 booleans MONDAY_WAS_RUNNING and TUESDAY_WAS RUNNING (you could use just the existing boolean by setting that to false in the buttonTue listener doing the Tuesday processing in the else (without an if) ).
e.g. :-
FirstActivity class :-
public static boolean MONDAY_WAS_RUNNING;
public static boolean TUESDAY_WAS_RUNNING;
..........
buttonMon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MONDAY_WAS_RUNNING = true;
TUESDAY_WAS_RUNNING = false;
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
intent.putExtra(BUTTON_KEY1, BUTTON_VALUE);
startActivity(intent);
} });
buttonTue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TUESDAY_WAS_RUNNING = true;
MONDAY_WAS_RUNNING = false;
Intent i = new Intent(FirstActivity.this, MainActivity.class);
i.putExtra(BUTTON_KEY2, BUTTON_VALUE2);
startActivity(i);
} });}}
MyAdapter :-
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
holder.textViewModel.setText(training.get(position).getExercise());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v) {
if (FirstActivity.MONDAY_WAS_RUNNING)
{Intent intent = new Intent(c, DetailActivity.class);
intent.putExtra(KEY_MON, VALUE_MON);
intent.putExtra("id", training.get(position).getId());
intent.putExtra("exercise", training.get(position).getExercise());
intent.putExtra("weight", training.get(position).getWeight());
intent.putExtra("repeat", training.get(position).getRepeat());
intent.putExtra("series", training.get(position).getSeries());
c.startActivity(intent);
} else if (FirstActivity.TUESDAY_WAS_RUNNING)
{Intent intent2 = new Intent(c, DetailActivity.class);
intent2.putExtra(KEY_TUE, VALUE_TUE);
intent2.putExtra("id", training.get(position).getId());
intent2.putExtra("exercise", training.get(position).getExercise());
intent2.putExtra("weight", training.get(position).getWeight());
intent2.putExtra("repeat", training.get(position).getRepeat());
intent2.putExtra("series", training.get(position).getSeries());
c.startActivity(intent2);
}}});}
However I'd probably go for :-
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
holder.textViewModel.setText(training.get(position).getExercise());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v) {
Intent intent = new Intent(c, DetailActivity.class);
if (FirstActivity.MONDAY_WAS_RUNNING) {
intent.putExtra(KEY_MON, VALUE_MON);
} else {
intent.putExtra(KEY_TUE, VALUE_TUE);
}
intent.putExtra("id", training.get(position).getId());
intent.putExtra("exercise", training.get(position).getExercise());
intent.putExtra("weight", training.get(position).getWeight());
intent.putExtra("repeat", training.get(position).getRepeat());
intent.putExtra("series", training.get(position).getSeries());
c.startActivity(intent);
});
}
Note! the above code has not been checked, rather it is in-principle code
I can make my database save images. They are display in the listView
but when i close the app, the data are erased.
DataBaseHandler.java:
public class DataBaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "Preguntas_y_Respuestas_Manager",
TABLE_PyR = "PreguntasYRespuestas",
KEY_ID = "id",
KEY_PREGUNTA = "pregunta",
KEY_RESPUESTA = "respuesta",
KEY_IMAGEURI = "imagen";
public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_PyR + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_PREGUNTA + " TEXT," + KEY_RESPUESTA + " TEXT, " + KEY_IMAGEURI + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PyR);
onCreate(db);
}
public void createPregunta_y_Respuesta(PreguntasYRespuestas pYr) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PREGUNTA, pYr.getPregunta());
values.put(KEY_RESPUESTA, pYr.getRespuesta());
values.put(KEY_IMAGEURI,pYr.get_imageUri().toString());
db.insert(TABLE_PyR, null, values);
db.close();
}
public PreguntasYRespuestas getPyR(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_PyR, new String[]{KEY_ID, KEY_PREGUNTA, KEY_RESPUESTA, KEY_IMAGEURI}, KEY_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
PreguntasYRespuestas preg_y_resp = new PreguntasYRespuestas(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), Uri.parse(cursor.getString(3)));
db.close();
return preg_y_resp;
}
public void deletePregunta(PreguntasYRespuestas pyr) {
SQLiteDatabase db = getWritableDatabase();
int cant = db.delete("PreguntasYRespuestas", "id=" + KEY_ID, null);
}
public int getPreguntasCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_PyR, null);
int count = cursor.getCount();
db.close();
cursor.close();
return count;
}
public int UpdatePregunta(PreguntasYRespuestas pyr) {
SQLiteDatabase db = getReadableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PREGUNTA, pyr.getPregunta());
values.put(KEY_RESPUESTA, pyr.getRespuesta());
values.put(KEY_IMAGEURI, pyr.get_imageUri().toString());
int rowsAffected = db.update(TABLE_PyR, values, KEY_ID + "=?", new String[]{String.valueOf(pyr.getId())});
db.close();
return rowsAffected;
}
public List<PreguntasYRespuestas> getAllPreguntas() {
List<PreguntasYRespuestas> pyr = new ArrayList<PreguntasYRespuestas>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_PyR, null);
if (cursor.moveToFirst()) {
do {
pyr.add(new PreguntasYRespuestas(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),Uri.parse(cursor.getString(3))));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return pyr;
}
}
RegistroDePreguntas_Cuestionario.java:
public class RegistroDePreguntas_Cuestionario extends AppCompatActivity {
private static final int EDIT = 0, DELETE = 1;
public Button agregar, iniciar;
public ImageView imagen;
public EditText et_pregunta, et_respuesta;
public ListView listView_preguntas;
Uri imageUri = null;
DataBaseHandler dbHandler;
int longClickedItemIndex;
ArrayAdapter<PreguntasYRespuestas> preguntasAdapter;
List<PreguntasYRespuestas> mListaPreguntas = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro_de_preguntas__cuestionario);
agregar = (Button) findViewById(R.id.agregar);
et_pregunta = (EditText) findViewById(R.id.Et_pregunta);
et_respuesta = (EditText) findViewById(R.id.Et_respuesta);
imagen = (ImageView)findViewById(R.id.imageView);
iniciar = (Button) findViewById(R.id.iniciar);
listView_preguntas = (ListView) findViewById(R.id.listview_preguntas);
dbHandler = new DataBaseHandler(getApplicationContext());
TabHost tabHost = (TabHost) findViewById(R.id.tabHost_Preg_Cuest);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("creator");
tabSpec.setContent(R.id.Creador);
tabSpec.setIndicator("Crear");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("visualizacion");
tabSpec.setContent(R.id.Visualizacion);
tabSpec.setIndicator("Ver");
tabHost.addTab(tabSpec);
registerForContextMenu(listView_preguntas);
listView_preguntas.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemIndex = position;
return false;
}
});
iniciar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegistroDePreguntas_Cuestionario.this, ActivityCuestionario.class));
}
});
agregar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PreguntasYRespuestas pyr = new PreguntasYRespuestas(dbHandler.getPreguntasCount(), String.valueOf(et_pregunta.getText()), String.valueOf(et_respuesta.getText()),imageUri);
if (!preguntaExists(pyr)) {
dbHandler.createPregunta_y_Respuesta(pyr);
mListaPreguntas.add(pyr);
preguntasAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Tu pregunta ha sido aƱadida", Toast.LENGTH_SHORT).show();
et_pregunta.setText("");
et_respuesta.setText("");
imageUri = null;
return;
}
Toast.makeText(getApplicationContext(), "Ya existe una pregunta igual, no pueden haber 2 preguntas iguales", Toast.LENGTH_SHORT).show();
}
});
imagen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Contact Image"),1);
}
});
et_pregunta.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
agregar.setEnabled(String.valueOf(et_pregunta.getText()).trim().length() > 0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
if (dbHandler.getPreguntasCount() != 0) {
mListaPreguntas.addAll(dbHandler.getAllPreguntas());
populateList();
}
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderIcon(R.drawable.edit);
//Icon made by [http://www.flaticon.com/authors/madebyoliver] from www.flaticon.com
menu.setHeaderTitle("Opciones");
menu.add(Menu.NONE, DELETE, menu.NONE, "Eliminar pregunta");
}
public void onActivityResult(int reqCode, int resCode, Intent data){
if (resCode==RESULT_OK){
if (reqCode==1){
imageUri = data.getData();
imagen.setImageURI(data.getData());
}
}
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case EDIT:
dbHandler.UpdatePregunta(mListaPreguntas.get(longClickedItemIndex));
preguntasAdapter.notifyDataSetChanged();
break;
case DELETE:
dbHandler.deletePregunta(mListaPreguntas.get(longClickedItemIndex));
mListaPreguntas.remove(longClickedItemIndex);
preguntasAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private boolean preguntaExists(PreguntasYRespuestas pyr) {
String pregunta = pyr.getPregunta();
int preguntaCount = mListaPreguntas.size();
for (int i = 0; i < preguntaCount; i++) {
if (pregunta.compareToIgnoreCase(mListaPreguntas.get(i).getPregunta()) == 0)
return true;
}
return false;
}
public void populateList() {
preguntasAdapter = new mListAdapter();
listView_preguntas.setAdapter(preguntasAdapter);
}
public class mListAdapter extends ArrayAdapter<PreguntasYRespuestas> {
public mListAdapter() {
super(RegistroDePreguntas_Cuestionario.this, R.layout.listview_item, mListaPreguntas);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
PreguntasYRespuestas currentPregunta = mListaPreguntas.get(position);
TextView tv_pregunta = (TextView) view.findViewById(R.id.tv_pregunta);
tv_pregunta.setText(currentPregunta.getPregunta());
TextView tv_respuesta = (TextView) view.findViewById(R.id.tv_respuesta);
tv_respuesta.setText(currentPregunta.getRespuesta());
ImageView imageView_Lista = (ImageView) view.findViewById(R.id.imageView_Lista);
imageView_Lista.setImageURI(currentPregunta.get_imageUri());
return view;
}
}
}
I am building a training log that uses an sqlite database to save what the user inputs. Currently, I only have an add method that appends to the database, but am unsure as to how to create a delete method that removes the row created. The user data is initially created and added in TrainingLogCreate (class), which accesses DBAdapter's (Class) add method. What can I add to my remove method in DBAdapter to be able to remove a user entry?
TrainingLogCreate:
public class TrainingLogCreate extends AppCompatActivity {
EditText nameTxt;
EditText posTxt;
Button savebtn;
Context context = this;
public TrainingLogCreate() {
// Required empty public constructor
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_log_create);
savebtn = (Button) findViewById(R.id.saveButton);
nameTxt = (EditText) findViewById(R.id.exercizeActivity);
posTxt = (EditText) findViewById(R.id.exercizeDetails);
final DBAdapter db = new DBAdapter(this);
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String datetime;
try {
Date date = new Date();
datetime = dateFormat.format(date);
} finally {
}
final String dateTxt = datetime;
savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//OPEN
db.openDB();
//INSERT
long result = db.add(nameTxt.getText().toString(), posTxt.getText().toString(), dateTxt.toString());
if (result > 0) {
nameTxt.setText("");
posTxt.setText("");
} else {
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
}
//CLOSE DB
db.close();
//Open Fragment
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mif = getMenuInflater();
mif.inflate(R.menu.training_create_menu, menu);
getActionBar().show();
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_save:
//add save functionality
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
DBAdapter:
public class DBAdapter {
//COLUMNS
static final String ROWID="id";
static final String NAME = "name";
static final String POSITION = "position";
static final String DATE = "date";
//DB PROPERTIES
static final String DBNAME="m_DB";
static final String TBNAME="m_TB";
static final int DBVERSION='1';
static final String CREATE_TB="CREATE TABLE m_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT NOT NULL,position TEXT NOT NULL,date TEXT NOT NULL);";
final Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(FragmentActivity ctx) {
// TODO Auto-generated constructor stub
this.c=ctx;
helper=new DBHelper(c);
}
// INNER HELPER DB CLASS
private static class DBHelper extends SQLiteOpenHelper
{
public DBHelper(Context context ) {
super(context, DBNAME, null, DBVERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
try
{
db.execSQL(CREATE_TB);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w("DBAdapetr","Upgrading DB");
db.execSQL("DROP TABLE IF EXISTS m_TB");
onCreate(db);
}
}
// OPEN THE DB
public DBAdapter openDB()
{
try
{
db=helper.getWritableDatabase();
}catch(SQLException e)
{
Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
}
return this;
}
//CLOSE THE DB
public void close()
{
helper.close();
}
//INSERT INTO TABLE
public long add(String name,String pos, String date)
{
try
{
ContentValues cv=new ContentValues();
cv.put(NAME, name);
cv.put(POSITION, pos);
cv.put(DATE, date);
return db.insert(TBNAME, ROWID, cv);
}catch(SQLException e)
{
e.printStackTrace();
}
return 0;
}
//REMOVE FROM TABLE
public long remove(String name)
{
}
//GET ALL VALUES
public Cursor getAllNames()
{
String[] columns={ROWID,NAME,POSITION,DATE};
return db.query(TBNAME, columns, null, null, null, null, null);
}
}
You can have a delete method like this
public void deleteInterestId(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_TIMEKEEPER, KEY_ID + "=?", new String[]{String.valueOf(id)});
db.close();
}
You have to pass the id which you want to delete. You have to customize this method a bit but it will give you an idea
And the most important thing for delete is that you have to also create a column named id and increase it's value as record are inserted. Because you can't delete on base of id that is created automatically by database