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
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 have 3 java classes (MainActivity, DatabaseOpenHelper and DatabaseAccess)
My add and show buttons work perfectly, but not my delete button. Add adds name and nickname into the database, show shows the list of names in the same layout under the buttons.
Here is my code in MainActivity.class
public class MainActivity extends AppCompatActivity {
public EditText name123, dogName, dogNickname;
public Button query_button, add_button, show_button, delete_button;
public TextView result_address;
public ListView listView;
ArrayList<String> naziv = new ArrayList<>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name123 = findViewById(R.id.name);
query_button = findViewById(R.id.query_button);
result_address = findViewById(R.id.result);
dogName = findViewById(R.id.et_dogName);
dogNickname = findViewById(R.id.et_dogNickname);
add_button = findViewById(R.id.add_button);
show_button = findViewById(R.id.show_button);
delete_button = findViewById(R.id.delete_button);
listView = findViewById(R.id.doglistview);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item, naziv);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
long result = databaseAccess.add(dogName.getText().toString(), dogNickname.getText().toString());
if(result > 0){
dogName.setText("");
dogNickname.setText("");
} else {
Toast.makeText(getApplicationContext(), "Dodaj ime i nadimak", Toast.LENGTH_SHORT).show();
}
databaseAccess.close();
}
});
show_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
naziv.clear();
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
Cursor cnn = databaseAccess.getAllNames();
while (cnn.moveToNext()){
String name = cnn.getString(0);
naziv.add(name);
}
listView.setAdapter(adapter);
databaseAccess.close();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), naziv.get(position), Toast.LENGTH_SHORT).show();
}
});
//setting onclicklistener to query button
query_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//create the instance of database access class and open database connection
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
//getting sting value of edittext
String n = name123.getText().toString();
String address = databaseAccess.getAddress(n);//getAddress method to get address
//setting text to result field
result_address.setText(address);
databaseAccess.close();
}
});
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
Integer deletedRows = databaseAccess.deleteData("id_dogName");
if (deletedRows > 0){
Toast.makeText(MainActivity.this, "Deleted data", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "Data not deleted", Toast.LENGTH_SHORT).show();
}
databaseAccess.close();
}
});
}
}
And here is the code from DatabaseAccess.class:
public class DatabaseAccess {
static final String NAME = "name_dogName";
static final String NICKNAME = "nickname_dogName";
static final String TBNAME = "dogName";
static final String ROWID = "id_dogName";
private SQLiteOpenHelper openHelper;
private SQLiteDatabase db;
private static DatabaseAccess instance;
Cursor c = null;
//private constructor so that object creation from outside the class is avoided
private DatabaseAccess(Context context)
{
openHelper = new DatabaseOpenHelper(context);
}
//to return the single instance of database
public static DatabaseAccess getInstance(Context context)
{
if(instance == null)
{
instance = new DatabaseAccess(context);
}
return instance;
}
//to open the database
public void open()
{
db = openHelper.getWritableDatabase();
}
//closing the database connection
public void close()
{
if(db!=null)
{
db.close();
}
}
//method to query and return the results from database
//query for address by passing name
public String getAddress(String name)
{
c = db.rawQuery("select nickname_dogName from dogName where name_dogName = ?", new String[]{name});
String nickname = "";
while (c.moveToNext())
{
String address = c.getString(0);
nickname += address;
}
return nickname;
}
//add
public long add(String name, String nickname){
try {
ContentValues contentValues = new ContentValues();
contentValues.put(NAME, name);
contentValues.put(NICKNAME, nickname);
return db.insert(TBNAME, ROWID, contentValues);
} catch (SQLException e){
e.printStackTrace();
}
return 0;
}
public Cursor getAllNames (){
String[] columns = {NAME, ROWID, NICKNAME};
return db.query(TBNAME, columns, null, null, null, null, null);
}
public Integer deleteData (String id){
return db.delete(TBNAME, "id_dogName", new String[]{id});
}
}
When I click on my phone on the delete button it throws me out of the app. How to correct my code and make the delete button delete a selected item from the list?
something wrong in the second argument, your where clause should include "=?"
public Integer deleteData (String id){
return db.delete(TBNAME, "id_dogName=?", new String[]{id});
}
I have a problem with database in android.
I'd like to collect data from an activity then transfer them to another activity that should show them into a ListView and save them into the DB.
The problem is that the app shows only the first item in the listview and I don't know if all data are saved into the DB. When I try to insert a new item, the app probably overrides the first item and shows the newest one.
Thanks a lot!
public class HomeActivity extends AppCompatActivity {
Button addPets;
private ListView mainListView;
private ArrayList<User> listUser;
private ArrayAdapter adapter;
private DBAdapter dbAdapter;
DBOpenHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
addPets = (Button)findViewById(R.id.add_friends);
addPets.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent apriRegistraPet = new Intent(HomeActivity.this, RegisterActivity.class);
startActivity(apriRegistraPet);
}
});
dbAdapter = DBAdapter.getInstance(this);
mainListView = (ListView)findViewById(R.id.elenco_pets);
listUser = new ArrayList<User>();
adapter = new ArrayAdapter<User>(this, android.R.layout.simple_list_item_1, listUser);
mainListView.setAdapter(adapter);
mainListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
onLongClick(position, mainListView);
return true;
}
});
}
private void addNewItem(User user) {
long idx = dbAdapter.insertUser(user);
user.setId(idx);
listUser.add(0, user);
adapter.notifyDataSetChanged();
}
private void onLongClick(final int position, final ListView listView){
User user = (User)listView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "Deleted Item", Toast.LENGTH_LONG).show();
if(!dbAdapter.deleteUser(user)){
return;
}
listUser.remove(user);
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
super.onResume();
dbAdapter.open();
fillData();
Bundle extras = getIntent().getExtras();
if(extras != null){
String nome = extras.getString("Nome");
String razza = extras.getString("Razza");
String sesso = extras.getString("Sesso");
User user = new User(0, nome, razza, sesso, 10, 2000);
addNewItem(user);
}
}
public void fillData(){
Cursor cursor = dbAdapter.getAllEntries();
this.listUser.clear();
cursor.moveToFirst();
while(!cursor.isAfterLast()){
long idx = cursor.getLong(cursor.getColumnIndex(DBContract.AttributiRegistrazione._ID));
String nome = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.NOME));
String razza = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.RAZZA));
String sesso = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.SESSO));
this.listUser.add(0, new User(idx, nome, razza, sesso, 10, 2000));
cursor.moveToNext();
}
cursor.close();
adapter.notifyDataSetChanged();
}
And this is Register Activity
public class RegisterActivity extends AppCompatActivity {
ImageButton settaImmagine;
String imgDecodableString;
Spinner sprazza;
Spinner spsesso;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Clicco V e mette nella listview
ImageButton salva = (ImageButton)findViewById(R.id.button_salva);
salva.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText editText = (EditText)findViewById(R.id.name);
sprazza = (Spinner)findViewById(R.id.spinner_razza);
String razza = sprazza.getSelectedItem().toString();
spsesso = (Spinner)findViewById(R.id.spinner_sesso);
String sesso = spsesso.getSelectedItem().toString();
Intent resultIntent = new Intent(RegisterActivity.this, HomeActivity.class);
resultIntent.putExtra("Nome", editText.getText().toString());
resultIntent.putExtra("Razza", razza);
resultIntent.putExtra("Sesso", sesso);
startActivity(resultIntent);
}
});
DBAdapter class;
public class DBAdapter {
private static final String TAG = "DBAdapter";
private static DBAdapter dbAdapter;
private static DBOpenHelper dbOpenHelper;
private SQLiteDatabase db;
public synchronized static DBAdapter getInstance(Context context){
if(dbAdapter==null) {
dbAdapter = new DBAdapter(context.getApplicationContext());
}
return dbAdapter;
}
private DBAdapter(Context context) {dbOpenHelper = DBOpenHelper.getInstance(context);}
public DBAdapter open() throws SQLException{
try{
db = dbOpenHelper.getWritableDatabase();
}
catch (SQLException e){
Log.e(TAG, e.toString());
throw e;
}
return this;
}
public void close() {
db.close();
}
public long insertUser (User user){
Log.v(TAG, "Inserisci un User to DB: " +user.getNome());
long idx = db.insert(DBContract.AttributiRegistrazione.NOME_TABELLA, null, user.getAsContentValue());
user.setId(idx);
Log.v(TAG, "Added user with ID: "+idx);
return idx;
}
public boolean deleteUser (User user){
Log.v(TAG, "Removing User: " + user.getClass());
return db.delete(DBContract.AttributiRegistrazione.NOME_TABELLA,
DBContract.AttributiRegistrazione.NOME + "=" + user.getNome(), null) == 1;
}
public boolean deleteUser(String name){
Log.v(TAG, "Removing user: " + name);
return db.delete(DBContract.AttributiRegistrazione.NOME_TABELLA,
DBContract.AttributiRegistrazione.NOME + "=" + name, null) == 1;
}
public Cursor getAllEntries(){
return db.query(DBContract.AttributiRegistrazione.NOME_TABELLA,
null, null, null, null, null, null);
}
ERROR LOG
E/SQLiteLog: (1) table Registrazione has no column named Anno_nascita 04-10 13:57:21.142 10175-10175/com.b.uzzo.snappaw E/SQLiteDatabase: Error inserting Anno_nascita=2000 Peso=10.0 Nome=simone Sesso=Maschio Razza=Akita Inu
android.database.sqlite.SQLiteException: table Registrazione has no column named Anno_nascita (code 1): , while compiling: INSERT INTO Registrazione(Anno_nascita,Peso,Nome,Sesso,Razza) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:898)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:509)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1500)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1373)
at com.b.uzzo.snappaw.DBAdapter.insertUser(DBAdapter.java:49)
at com.b.uzzo.snappaw.HomeActivity.addNewItem(HomeActivity.java:105)
at com.b.uzzo.snappaw.HomeActivity.onResume(HomeActivity.java:140)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6770)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3522)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3591)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2825)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1542)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1085)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:946)
But it's created in DBContract class
public class DBContract {
static final String DB_NAME = "RegistrazioneCuccioli";
static final int DB_VERSION = 1;
static abstract class AttributiRegistrazione implements BaseColumns{
static final String NOME_TABELLA = "Registrazione";
static final String NOME = "Nome";
static final String RAZZA = "Razza";
static final String SESSO = "Sesso";
static final String PESO = "Peso";
static final String ANNO_NASCITA = "Anno_nascita";
}
}
In fillData method of HomeActivity class, You are adding data into Arraylist using list.add(0,new User()),which add your data into 0 index, that is cause of your problem. You should have to call list.add(user)
Try this updated Code:
public void fillData(){
Cursor cursor = dbAdapter.getAllEntries();
this.listUser.clear();
if (cursor.moveToFirst()){
do {
long idx = cursor.getLong(cursor.getColumnIndex(DBContract.AttributiRegistrazione._ID));
String nome = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.NOME));
String razza = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.RAZZA));
String sesso = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.SESSO));
User user = new User(idx, nome, razza, sesso, 10, 2000);
this.listUser.add(user);
}while(cursor.moveToNext());
}
cursor.close();
adapter.notifyDataSetChanged();}
I have create the recycerview and this recycerview display the Person image ,person name and + button when i have press + button change the button image like true.and after recycerview bottom one button this button click all data show the next activity..
My Adapter
public class BuildCustomAdapter extends RecyclerView.Adapter<BuildCustomAdapter.MyViewHolder> implements Filterable {
private List<People> peopleList;
private List<People> peopleListCopy;
private ItemFilter mFilter = new ItemFilter();
public BuildCustomAdapter(List<People> buildList) {
this.peopleList = buildList;
this.peopleListCopy = new ArrayList<>();
peopleListCopy.addAll(buildList);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.build_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
People people = peopleList.get(position);
byte[] decodedString = Base64.decode(people.getPeopleImage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.ivPeopleImage.setImageBitmap(decodedByte);
holder.tvPersonName.setText(people.getPeopleName());
holder.button.setSelected(people.isSelected());
holder.button.setOnClickListener(new onSelectListener(position));
}
#Override
public int getItemCount() {
return peopleList.size();
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemFilter();
}
return mFilter;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
// public ImageView ivPeopleImage;
public TextView tvPersonName;
public Button button;
public CircularImageView ivPeopleImage;
public MyViewHolder(View itemView) {
super(itemView);
ivPeopleImage = (CircularImageView) itemView.findViewById(R.id.ivPerson);
tvPersonName = (TextView) itemView.findViewById(R.id.tvPersonName);
button = (Button) itemView.findViewById(R.id.addbn);
}
}
private class ItemFilter extends Filter {
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List<People> filterList = new ArrayList<>();
for (int i = 0; i < peopleListCopy.size(); i++) {
if ((peopleListCopy.get(i).getPeopleName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
People peopleName = peopleListCopy.get(i);
filterList.add(peopleName);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = peopleListCopy.size();
results.values = peopleListCopy;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
peopleList = (List<People>) results.values;
notifyDataSetChanged();
}
}
private class onSelectListener implements View.OnClickListener {
int mPosition;
public onSelectListener(int position) {
mPosition = position;
}
#Override
public void onClick(View view) {
view.setSelected(!view.isSelected());
People people = peopleList.get(mPosition);
people.setSelected(!people.isSelected());
notifyDataSetChanged();
}
}
Activity
public class BulidActivity extends AppCompatActivity {
private List<People> peopleList = new ArrayList<>();
private List<People> peopleListCopy = new ArrayList<>();
private RecyclerView recyclerView;
private BuildCustomAdapter buildCustomAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bulid);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
BuildData();
peopleListCopy.addAll(peopleList);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
buildCustomAdapter = new BuildCustomAdapter(peopleList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(buildCustomAdapter);
AddTxt();
BtnBuildNow();
}
private void BtnBuildNow() {
Button btnnuildnow = (Button) findViewById(R.id.btn_build_now);
btnnuildnow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BulidActivity.this, AlertList.class);
startActivity(intent);
}
});
}
private void AddTxt() {
EditText editTxt = (EditText) findViewById(R.id.etSearch);
editTxt.setTextColor(Color.WHITE);
editTxt.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.setFocusable(true);
v.setFocusableInTouchMode(true);
return false;
}
});
editTxt.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() <= 0) {
peopleList.clear();
peopleList.addAll(peopleListCopy);
recyclerView.setAdapter(null);
buildCustomAdapter = new BuildCustomAdapter(peopleList);
recyclerView.setAdapter(buildCustomAdapter);
} else {
buildCustomAdapter.getFilter().filter(s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private List<People> BuildData() {
DataBaseHelper db = new DataBaseHelper(getApplicationContext());
try {
db.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
if (db.open()) {
peopleList = db.getPeople();
}
return peopleList;
}
Model class
public class People implements Serializable {
private String peopleImage;
private String peopleName;
private boolean selected;
public void setPeopleName(String peopleName) {
this.peopleName = peopleName;
}
public String getPeopleName() {
return peopleName;
}
public void setPeopleImage(String peopleImage) {
this.peopleImage = peopleImage;
}
public String getPeopleImage() {
return peopleImage;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
DatabaseHelper.class
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String DB_PATH = "/data/data/databasename/databases/";
private static final String DB_NAME = "alertme.db";
private final String TABLE_PEOPLE = "people";
private final String TABLE_CATEGORY = "category";
private final String CATEGORY_NAME = "name";
private final String ID = "id";
private final String CATEGORY_ID = "category_id";
private final String PEOPLE_IMAGE = "image";
private final String PEOPLE_NAME = "name";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public boolean open() {
try {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
return true;
} catch (SQLException sqle) {
myDataBase = null;
return false;
}
}
public List<People> getPeople(String category_id) {
List<People> peoples = new ArrayList<>();
try {
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery("select * from people where category_id = " + category_id, null);
while (cursor.moveToNext()) {
String peopleName = cursor.getString(cursor.getColumnIndex(PEOPLE_NAME));
String peopleImage = cursor.getString(cursor.getColumnIndex(PEOPLE_IMAGE));
People people = new People();
people.setPeopleName(peopleName);
people.setPeopleImage(peopleImage);
peoples.add(people);
}
} catch (Exception e) {
Log.d("DB", e.getMessage());
}
return peoples;
}
public List<Category> getCategory() {
List<Category> categoryList = new ArrayList<>();
try {
String query = " SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()) {
int categoryID = cursor.getInt(cursor.getColumnIndex(ID));
String categoryName = cursor.getString(cursor.getColumnIndex(CATEGORY_NAME));
Category category = new Category();
category.setId(categoryID);
category.setCategoryName(categoryName);
categoryList.add(category);
}
} catch (Exception e) {
Log.d("DB", e.getMessage());
}
return categoryList;
}
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
First you should implement Serializable interface in your Build model class like this :-
public class Build implements Serializable{
//Content will be as it is
}
Change your clickListener like this :-
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build.setSelected(!build.isSelected());
if (build.isSelected()) {
holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
Intent intent = new Intent(context, youractivity.class)
intenet.putExtra("build",build);
context.startActivity(intent);
} else
holder.button.setBackgroundResource(R.drawable.add_button_icon);
}
});
In the onCreate method of receiving activity write this :-
Build build = (Build) getIntent().getSerializableExtra("build");
Add Intent in below Method,
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build.setSelected(!build.isSelected());
if (build.isSelected()) {
holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
Intent intent = new Intent(context, youractivity.class)
intenet.putExtra("key","value");
context.startActivity(intent);
} else
holder.button.setBackgroundResource(R.drawable.add_button_icon);
}
});
Huge mistak that you register to the click event on your ViewHolder! you will get diffrent position from the actual because when android use notifyItemMoved the viewBindHolder will not be called and than you got the wrong position.
and in the click listener implementation you should pass Intent with your data
Below given is my code.
I have 2 classes: Dbhelper.java and RssActivity.java
Basically I have made a students table and my code is creating the table, but values are not being inserted into it.
There are 2 textboxes: one is for entering name and other for entering roll no.
I want that the values should be inserted when the roll no lies in the range 00113202709 to 12013203709
I want that the values should be taken from the 2 textboxes editText1 and editText2 and be inserted in my database table.
Thanks for any help.
Dbhelper.java:
public class Dbhelper extends SQLiteOpenHelper {
//private static final String TAG = Dbhelper.class.getSimpleName();
public static final String db_name = "member.db";
public static final int db_version = 1;
public final String TABLE = "students";
public static final String C_ID = BaseColumns._ID;
public static final String C_Name = "SName";
public static final String C_ENo = "Enroll No";
private Context context;
public Dbhelper(Context context) {
super(context, db_name, null, db_version);
this.context=context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = String.format(
"create table %s (%s TEXT primary key, %s TEXT, %s TEXT )",
TABLE, C_ID, C_Name, C_ENo);
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("drop table if exists " + TABLE);
this.onCreate(db);
}
}
RssActivity.java:
public class RssActivity extends Activity implements OnClickListener {
TextView Title;
EditText Name, ENo;
Button but;
public String n1 = "001";
public String n2 = "120";
public String s1, s2, s3;
Dbhelper obj;
SQLiteDatabase db;
ContentValues val;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Title = (TextView) findViewById(R.id.textView1);
Name = (EditText) findViewById(R.id.editText2);
ENo = (EditText) findViewById(R.id.editText1);
but = (Button) findViewById(R.id.button1);
but.setOnClickListener(this);
obj=new Dbhelper(RssActivity.this);
db=obj.getWritableDatabase();
}
public void onClick(View v) {
String name = Name.getText().toString();
String enr = ENo.getText().toString();
try {
if (name.equals("")) {
Name.setError(getText(R.string.Empty));
Toast.makeText(this, R.string.Empty, Toast.LENGTH_LONG).show();
} else if ((ENo.getText().toString().length() == 0)) {
ENo.setError(getText(R.string.Empty));
Toast.makeText(this, R.string.Empty, Toast.LENGTH_LONG).show();
} else if ((ENo.getText().toString().length() < 11))
{
ENo.setError(getText(R.string.Invalid));
Toast.makeText(this, R.string.Invalid, Toast.LENGTH_LONG)
.show();
}
else
{
s1 = "000";
s2 = "00000000";
throw new Exception();
}
}
catch (Exception e) {
e.printStackTrace();
s1 = enr.substring(0, 3);
s2 = enr.substring(3, 11);
s3 = "13202709";
int r1 = s1.compareTo(n1);
int r2 = s1.compareTo(n2);
if (s2.equals(s3)) {
if (r1 == 0 || r2 == 0) {
Toast.makeText(this, R.string.Success, Toast.LENGTH_LONG)
.show();
val=new ContentValues();
val.clear();
val.put(obj.C_ID, s1);
val.put(obj.C_Name, name);
val.put(obj.C_ENo,enr);
db.insert(obj.TABLE, null, val);
db.close();
} else if (r1 < 0 || r2 > 0) {
Toast.makeText(this, R.string.Fail, Toast.LENGTH_LONG)
.show();
} else if (r1 > 0 || r2 < 0) {
Toast.makeText(this, R.string.Success, Toast.LENGTH_LONG)
.show();
}
}
else
Toast.makeText(this, R.string.Fail, Toast.LENGTH_LONG).show();
}
db.close();
obj.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.item1:
startActivity(new Intent(this, Welcomescreen.class));
this.finish();
break;
case R.id.item2:
this.finish();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Welcomescreen.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
this.finish();
}
}