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 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 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 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
I am trying to create a shopping cart app and everything was going great but now i am stuck for last three day did search lot in stackoverflow but could not get a answer.I am populating listview from server and there is two buttons in each row plus(for adding quantity) and minus for (decrements it). This is the screen where i am adding quantity to cart.
I am trying to insert row to sqlite database upon clicking either of two buttons and i have achieved this and i am show these data in next activity inside a listview. Here my problem starts when i insert data it shows it properly but during updation it is showing strange behavior. If i click on first three rows the insertion and updation working fine but if i scroll down and click on any item then instead of updating each time its inserting.. I know this question is quite big and lengthy but i could not find a good way to summarize it sorry.. Please help me thanks ..
This is the screen which i am getting as output.
Here is my ListView class.
public class MyFragment extends Fragment implements View.OnClickListener{
int mCurrentPage;
private ListView listView;
RecyclerView recyclerView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private ProgressDialog pDialog;
private List<FeedItem> productsInCart = new ArrayList<FeedItem>();
private RelativeLayout content;
private SharedPreferences preference;
TextView badge,prices;
int totalCount=0,newCount = 0;
int lastCount;
int totalPrice;
SQLiteDatabase dataBase;
public static final String TOTAL_COUNT = "count";
DBHelper mHelper;
boolean isUpdate;
String userId,price,pname,position;
private Button checkOut;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Getting the arguments to the Bundle object */
Bundle data = getArguments();
/** Getting integer data of the key current_page from the bundle */
mCurrentPage = data.getInt("current_page", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
recyclerView= (RecyclerView) v.findViewById(R.id.my_recycler_view);
content = (RelativeLayout)v.findViewById(R.id.content);
badge = (TextView)v.findViewById(R.id.all_comments);
checkOut = (Button)v.findViewById(R.id.checkOut);
prices = (TextView)v.findViewById(R.id.price);
feedItems = new ArrayList<FeedItem>();
new JSONAsyncTask()
.execute("http://api.androidhive.info/feed/feed.json");
listAdapter = new FeedListAdapter(getActivity(), feedItems);
recyclerView.setAdapter(listAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
listAdapter.setOnAddNum(this);
listAdapter.setOnSubNum(this);
mHelper=new DBHelper(getActivity());
content.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(getActivity(),CheckOutFooter.class);
startActivity(i);
getActivity().overridePendingTransition
(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
}
});
checkOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (userId != null){
Intent i = new Intent(getActivity(),CheckOut.class);
startActivity(i);
}
else{
Toast.makeText(getActivity(), "Cart is empty! Please add few products to cart.",
Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
// TODO Auto-generated method stub
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("feed");
for (int i = 0; i < jarray.length(); i++) {
JSONObject feedObj = jarray.getJSONObject(i);
// Actors actor = new Actors();
FeedItem item = new FeedItem();
item.setObservation(feedObj.optString("name"));
item.setSummary(feedObj.optString("timeStamp"));
item.setName(feedObj.optString("name"));
feedItems.add(item);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if(result == false){
Toast.makeText(getActivity(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
else{
listAdapter.notifyDataSetChanged();
}
pDialog.dismiss();
}
}
#Override
public void onClick(View view) {
Object tag = (Integer) view.getTag();
switch (view.getId()){
case R.id.btnAddToCart1:
// FeedItem item = feedItems.get(tag);
if (tag != null && tag instanceof Integer) {
int position = (Integer) tag;
int num =feedItems.get(position).getNum();
int price =feedItems.get(position).getPrice();
String pName = feedItems.get(position).getName();
String product_name = feedItems.get(position).getName();
num++;
feedItems.get(position).setNum(num);
feedItems.get(position).setPrice(position);
Toast.makeText(getActivity(),
product_name+ " is added to cart!", Toast.LENGTH_SHORT).show();
preference = getActivity().getSharedPreferences("STATE", Context.MODE_PRIVATE);
preference.edit().putString("QUANTITY", String.valueOf(num)).apply();
preference.edit().putString("PRICE", String.valueOf(num*position)).apply();
preference.edit().putString("PNAME",product_name).apply();
preference.edit().putString("POSITION",String.valueOf(position)).apply();
updateData();
listAdapter.notifyDataSetChanged();
}
break;
case R.id.btnAddToCart5:
if (tag != null && tag instanceof Integer) {
int position = (Integer) tag;
int num =feedItems.get(position).getNum();
int price =feedItems.get(position).getPrice();
if (num>0) {
num--;
feedItems.get(position).setNum(num);
feedItems.get(position).setPrice(position);
preference = getActivity().getSharedPreferences("STATE", Context.MODE_PRIVATE);
preference.edit().putString("QUANTITY", String.valueOf(num)).apply();
preference.edit().putString("PRICE", String.valueOf(num*position)).apply();
preference.edit().putString("POSITION",String.valueOf(position)).apply();
updateData();
listAdapter.notifyDataSetChanged();
}
else{
num= 0;
dataBase.delete(
DBHelper.TABLE_NAME,
DBHelper.KEY_ID + "="
+ (position+1), null);
listAdapter.notifyDataSetChanged();
}
}
break;
}
}
public void onResume(){
super.onResume();
}
private void updateData() {
preference =
getActivity().getSharedPreferences("STATE", Context.MODE_PRIVATE);
userId = preference.getString("QUANTITY", null);
price = preference.getString("PRICE", null);
pname = preference.getString("PNAME", null);
position = preference.getString("POSITION", null);
int counts = Integer.parseInt(position);
if(userId == null){
badge.setText("0");
}
else{
checkOut.setEnabled(true);
badge.setText(String.valueOf(userId));
dataBase = mHelper.getReadableDatabase();
/*Cursor curs = dataBase.rawQuery("SELECT SUM(price) FROM cart", null);
if(curs.moveToFirst())
{
int total = curs.getInt(0);
System.out.println("Total Sum of Price : "+total);
prices.setText(String.valueOf(total)+" Rs/-");
}
*/
Cursor cur = null;
String query = "SELECT * FROM " + DBHelper.TABLE_NAME +
" WHERE " +DBHelper.KEY_ID+"=?;" ;
cur = dataBase.rawQuery(query,new String[] {String.valueOf(counts+1)});
if((cur != null) && (cur.getCount() > 0)){
dataBase = mHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBHelper.KEY_COUNT,userId);
cv.put(DBHelper.KEY_PRICE, price);
cv.put(DBHelper.KEY_PNAME, pname);
System.out.println("Database values : "+cv);
dataBase.update(DBHelper.TABLE_NAME, cv, DBHelper.KEY_ID+" = '" +
String.valueOf(counts+1) + "'", null);
cur.close();
}
else{
dataBase = mHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBHelper.KEY_COUNT,userId);
cv.put(DBHelper.KEY_PRICE, price);
cv.put(DBHelper.KEY_PNAME, pname);
System.out.println("Database values : "+cv);
dataBase.insert(DBHelper.TABLE_NAME, null, cv);
cur.close();
}
}
}
}
My checkout page where i am showing data from sqlite.
public class CheckOut extends AppCompatActivity{
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> product_Name = new ArrayList<String>();
private ArrayList<String> product_Quantity = new ArrayList<String>();
private ArrayList<String> product_Price = new ArrayList<String>();
private ArrayList<Integer> quantityList = new ArrayList<Integer>();
private ArrayList<Integer> amountList = new ArrayList<Integer>();
ListView recyclerView;
TextView quantity;
TextView amount;
Button pay;
DBHelper mHelper;
SQLiteDatabase dataBase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkout);
recyclerView= (ListView) findViewById(R.id.my_recycler_view);
amount = (TextView) findViewById(R.id.amount);
quantity = (TextView) findViewById(R.id.quantity);
pay = (Button) findViewById(R.id.pay);
mHelper = new DBHelper(this);
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DBHelper.TABLE_NAME, null);
int sum = 0;
int qty = 0;
userId.clear();
product_Name.clear();
product_Quantity.clear();
quantityList.clear();
amountList.clear();
product_Price.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_ID)));
product_Name.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_PNAME)));
product_Quantity.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_COUNT)));
product_Price.add(mCursor.getString(mCursor.getColumnIndex(DBHelper.KEY_PRICE)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(CheckOut.this,userId, product_Name, product_Price,product_Quantity);
recyclerView.setAdapter(disadpt);
mCursor.close();
quantityList = convertInteger(product_Quantity);
amountList = converAmountInteger(product_Price);
for (int i : quantityList){
qty = qty+i;
}
for (int s : amountList){
sum = sum +s;
}
amount.setText(String.valueOf(sum));
quantity.setText(String.valueOf(qty));
disadpt.notifyDataSetChanged();
}
private ArrayList<Integer> converAmountInteger(
ArrayList<String> product_Price2) {
// TODO Auto-generated method stub
ArrayList<Integer> result = new ArrayList<Integer>();
for(String amount : product_Price2) {
try {
//Convert String to Integer, and store it into integer array list.
result.add(Integer.parseInt(amount));
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + amount + " can not be an integer");
}
}
return result;
}
private ArrayList<Integer> convertInteger(
ArrayList<String> product_Quantity2) {
// TODO Auto-generated method stub
ArrayList<Integer> result = new ArrayList<Integer>();
for(String quantity : product_Quantity2) {
try {
//Convert String to Integer, and store it into integer array list.
result.add(Integer.parseInt(quantity));
} catch(NumberFormatException nfe) {
//System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + quantity + " can not be an integer");
}
}
return result;
}
Database class:
public class DBHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME="user.db";
public static final String TABLE_NAME="cart";
public static final String KEY_COUNT="cartItem";
public static final String KEY_PNAME="product_name";
public static final String KEY_ID="id";
public static final String KEY_PRICE="price";
public static final String KEY_CREATED_AT="created_at";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_COUNT+" INTEGER,"
+KEY_PNAME+" TEXT,"+KEY_PRICE+" INTEGER,"+ KEY_CREATED_AT
+ " DATETIME" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
UPDATE :
There was a little mistake i changed the column name instead of i created a unique key and its working fine..