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
My problem is how to pass Rating bar value in to another activity using another putExtra method?any one solve this problem?
Here is my First activity
public void giveRating(View v)
{
String Name = spinner.getSelectedItem().toString();
Float Rating = ratingBar.getRating();
String query = "insert into Rating values('"+Name+"',"+Rating+")";
try
{
sqLiteDatabase.execSQL(query);
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("DATA SAVED");
ab.show();
}catch (Exception e)
{
Log.e("InsertionException",""+e);
}
}
public void viewRating(View v)
{
try {
StringBuffer sb = new StringBuffer();
String query = "select * from Rating";
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
boolean res = cursor.moveToFirst();
if (res) {
do {
String Name = cursor.getString(0);
String Rating = cursor.getString(1);
sb.append(Name + ":" + Rating+"\n");
} while (cursor.moveToNext());
} else {
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("No data To read");
ab.show();
}
String value = sb.toString();
Intent i = new Intent(MainActivity.this, Items.class);
i.putExtra("k1", value);
startActivity(i);
}
catch (Exception e)
{
Log.e("ReadDataEXception",""+e);
}
Second Activity
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.items_layout);
textView = (TextView)findViewById(R.id.tv3);
textView1 = (TextView)findViewById(R.id.tv4);
Intent i = getIntent();
String name;
Bundle b = getIntent().getExtras();
name= b.getString("k1");
textView.setText(name);
textView.setTextSize(20);
Database Activity
public Database(Context c)
{
super(c,DBNAME,null,VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
String query = "create table Rating(Name TEXT,Rating REAL)";
db.execSQL(query);
}catch (Exception e)
{
Log.e("TableCreationException",""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
You could simply add another putExtra with keyName like
Intent i = new Intent(MainActivity.this, Items.class);
i.putExtra("name", name);
i.putExtra("rating",rating);
startActivity(i);
And get from Items activity
Intent i = getIntent();
String name;
String rating;
Bundle b = getIntent().getExtras();
name= b.getString("name");
rating= b.getString("rating");
textView.setText(name);
textView1.setText(rating);
textView.setTextSize(20);
Hope it is helpful for you.
I have a problem to exclude a date and this occurs only when it is not the last element to the first in my ArrayList.
Why does this happen and how to solve?
Example:
| ID |
:
Gil <- problem deleting this line
Rui <- problem deleting this line
Ana <- no problem
I'm implementing the example of this site:
http://www.tutorialspoint.com/android/android_sqlite_database.htm
error: Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
Code
public Integer deleteContact (Integer id, ArrayList<Integer> array_List)
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete("contacts", "id = ? ", new String[]{Integer.toString(id)});
db.close();
return id;
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
if ( rs.moveToFirst()) {
do {
if (rs != null && rs.getCount()!= 0 ){
id_To_Update = Value;
String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
String phon=rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));
String emai=rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
String Stree=rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence) nam);
name.setFocusable(false);
name.setClickable(false);
phone.setText((CharSequence) phon);
phone.setFocusable(false);
phone.setClickable(false);
email.setText((CharSequence) emai);
email.setFocusable(false);
email.setClickable(false);
street.setText((CharSequence) stree);
street.setFocusable(false);
street.setClickable(false);
place.setText((CharSequence) plac);
place.setFocusable(false);
place.setClickable(false);
}
} while (rs.moveToNext());
if (!rs.isClosed()) {
rs.close();
}
}
if (!rs.isClosed()) {
rs.close();
}
}
}
}
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);
phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);
email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);
street.setEnabled(true);
street.setFocusableInTouchMode(true);
street.setClickable(true);
place.setEnabled(true);
place.setFocusableInTouchMode(true);
place.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);
phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);
email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);
street.setEnabled(true);
street.setFocusableInTouchMode(true);
street.setClickable(true);
place.setEnabled(true);
place.setFocusableInTouchMode(true);
place.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
the error leads me for the start of this line:
String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
You should check if rs.moveToFist() return false.
If it is false, it means the cursor is empty, so when you try to get the value you have an android.database.CursorIndexOutOfBoundsException.
Your getData(int) return an empty cursor, because there is no record for the id you gave him.
To remove the data in your arrayList change :
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
By :
int idContacts =res.getInt(res.getColumnIndex(CONTACTS_ID));
array_list.add(idContacts, res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
Then when you want to remove a contact use :
array_list.remove(idDelete);
when I receive SMS my current activity close and don't know why, I just refresh my listview with adapter.notifyDataSetChanged. when I send message I can refresh it, it just work but not when I receive
here is my Broadcast Receiver
public class SMSReceiver extends BroadcastReceiver {
String from;
String msg;
long time;
PrintMessage pm = new PrintMessage();
#Override
public void onReceive(Context context, Intent intent) {
abortBroadcast();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
// Convertir les PDUs en messages
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
// Enfin, traiter les messages
for (SmsMessage message : messages) {
from = message.getOriginatingAddress();
msg = message.getMessageBody();
time = message.getTimestampMillis();
}
}
pm.printMessage();
}
}
then my code where i display message
public class PrintMessage extends AppCompatActivity implements Telephony.TextBasedSmsColumns {
String idPerso, numero, contact, msg, from;
long time;
Intent intent;
ArrayList<CreateMessageAdapter> list = new ArrayList<>();
ImageButton buttonSend;
EditText textSMS;
Toolbar toolbar;
MessageAdapter adapter;
String[] selection;
Cursor cursor;
TextView tv_toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_print_message);
toolbar = (Toolbar) findViewById(R.id.tool_bar_messa);
buttonSend = (ImageButton) findViewById(R.id.btnSend);
textSMS = (EditText) findViewById(R.id.Et_message);
tv_toolbar = (TextView) findViewById(R.id.tv_toolbar);
intent = getIntent();
idPerso = intent.getStringExtra("id");
numero = intent.getStringExtra("numero");
contact = intent.getStringExtra("contact");
selection = new String[]{
Telephony.Sms.THREAD_ID,
Telephony.Sms.BODY,
Telephony.Sms.TYPE,
Telephony.Sms.DATE,
Telephony.Sms.DATE_SENT,
};
printMessage();
setSupportActionBar(toolbar);
if (!contact.equals("no"))
tv_toolbar.setText(contact);
else
tv_toolbar.setText(numero);
tv_toolbar.setMaxWidth(550);
getSupportActionBar().setDisplayShowTitleEnabled(false); //enlever le titre originel
buttonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sms = textSMS.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(numero, null, sms, null, null);
long time = System.currentTimeMillis();
// Cursor cTmp = cr.query(uri, selection, Telephony.Sms.THREAD_ID + "='" + idPerso + "'", null, "date ASC");
// cTmp.moveToFirst();
// int typeTmp = cTmp.getInt(2);
list.add(new CreateMessageAdapter(2, sms, time));
textSMS.setText("");
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS faild, please try again later!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
public void printMessage() {
// Read stored sms
Uri uri = Telephony.Sms.CONTENT_URI;
ContentResolver cr = getContentResolver();
cursor = cr.query(uri, selection, Telephony.Sms.THREAD_ID + "='" + idPerso + "'", null, "date ASC");
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int type = cursor.getInt(2);
String body = cursor.getString(1);
long dateNumber = cursor.getLong(3);
long dateNumberSent = cursor.getLong(4);
if (type == 2)
list.add(new CreateMessageAdapter(type, body, dateNumber));
else if (type == 1 || type == 5 || type == 6)
list.add(new CreateMessageAdapter(type, body, dateNumberSent));
cursor.moveToNext();
}
adapter = new MessageAdapter(list, this);
ListView lv = (ListView) findViewById(R.id.lv_message);
lv.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
lv.setStackFromBottom(true);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
Toast.makeText(PrintMessage.this, "long clicked pos: " + pos, Toast.LENGTH_LONG).show();
return true;
}
});
}
public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenu.ContextMenuInfo menuInfo) {
}
}
replace adapter = new MessageAdapter(list, this);
with adapter = new MessageAdapter(list, PrintMessage.this);
in printMessage()
I've taken a look at most of the questions discussing this but can't seem to find anything that fixes my problem. I have a Custom Array adapter passing data to a list and i need the list to refresh once I've deleted an item, I understand that notifyDataSetChanged() should be my solution but have yet to make it work
sorry for my messy code
but i'm still learning :)
any help would be appreciated, thanx :)
My Adapter:
public class CustomBasketAdapter extends ArrayAdapter<String>
{
private String TAG ="Vik";
public String stringEmail= "";
public String stringStore= "";
private String product = "";
private String quantity = "";
private String store = "";
//String[] stringEmail={"stefan.grobler#gmail.com"};
private final Activity context;
private final String[] storename;
private final String[] itemprice;
private final String[] itemname;
private final String[] productquantity;
private final String[] basketlinetotal;
//public CustomListAdapter(Activity context, String[] itemname,String[] itemprice, Integer[] imgid) {
public CustomBasketAdapter(Activity context, String[] storename,String[] itemprice, String[] productquantity, String[] itemname, String[] basketlinetotal ) {
super(context, R.layout.viewbasket_layout, storename);
// TODO Auto-generated constructor stub
this.context=context;
this.storename=storename;
this.itemprice=itemprice;
this.itemname=itemname;
this.productquantity=productquantity;
this.basketlinetotal=basketlinetotal;
Intent intent = ((Activity) context).getIntent();
if (null != intent)
{
stringEmail = intent.getStringExtra("EmailAddress");
stringStore = intent.getStringExtra("StoreDescription");
}
Toast toast = Toast.makeText(getContext(),stringEmail, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 10);
//toast.show();
}
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.viewbasket_layout, null,true);
final TextView txtstore = (TextView) rowView.findViewById(R.id.txtstorename);
final TextView txtproduct = (TextView) rowView.findViewById(R.id.txtproduct);
final TextView txtquantity = (TextView) rowView.findViewById(R.id.txtquantity);
TextView txtprice = (TextView) rowView.findViewById(R.id.txtprice);
TextView txttotal = (TextView) rowView.findViewById(R.id.txttotal);
Button btnclear = (Button) rowView.findViewById(R.id.btnclearitem);
txtstore.setText(storename[position]);
txtproduct.setText(itemname[position]);
txtquantity.setText(productquantity[position]);
txtprice.setText(itemprice[position]);
txttotal.setText(basketlinetotal[position]);
btnclear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
product = txtproduct.getText().toString();
quantity = txtquantity.getText().toString();
store = txtstore.getText().toString();
DeleteFromBasket();
Toast toast = Toast.makeText(getContext(),"Item Cleared", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 10);
toast.show();
notifyDataSetChanged();
}
/*your onclick code*/
});
return rowView;
};
public void ChannelToService()
{
String SOAP_ACTION = "http://tempuri.org/ITHubServ/DeleteFromBasket";
String METHOD_NAME = "DeleteFromBasket";
String NAMESPACE = "http://tempuri.org/";
String URL = "http://www.buh34nart.co.za/THubServ.svc?wsdl";
String OrderLine = "";
try{
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
String basketline = stringEmail + "|" + store + "|" + product.replace("|", "") + "|" + quantity;
//OrderLine = OrderLine.substring(0,OrderLine.length() -1);
Request.addProperty("Line", basketline);
//Request.addProperty("UserPassword", txtPass.getText().toString());
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE transport= new HttpTransportSE(URL);
Object Response = null;
transport.call(SOAP_ACTION, soapEnvelope);
Response = soapEnvelope.getResponse();
// data = Response.toString().split("[\\x7C]");
//Log.i(TAG, "Result Order: " + Response);
//if(Response.toString().equals("1"))
//{
// runOnUiThread(new Runnable() {
// public void run() {
//Toast toast = Toast.makeText(LoginPage.this,"Incorrect Username/Password" +
//" Login Failed", Toast.LENGTH_LONG);
//toast.setGravity(Gravity.CENTER, 0, 10);
//toast.show();
//Not Registered or psw wrong or email wrong (forgot password)
// }
// });
//}
//else
//{
// if(Response.toString().equals("9"))
// {
// startActivity(new Intent("com.ctc.android.widget.TechnicalError"));
// // Probleem met system Technical
// }
// else
// {
//btnloginclick();
// }
// }
}
catch(Exception Ex) {}
}
public void DeleteFromBasket()
{
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
ProgressDialog progDailog = new ProgressDialog(getContext());
#Override
protected Void doInBackground(Void... params) {
Log.i(TAG, "doInBackground");
ChannelToService();
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
CustomBasketAdapter.this.clear();
CustomBasketAdapter.this.addAll();
CustomBasketAdapter.this.notifyDataSetChanged();
progDailog.dismiss();
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
super.onPreExecute();
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(true);
progDailog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
}
I think that your problem in that you aren't deleting the item in the string array. You should change
CustomBasketAdapter.this.clear();
CustomBasketAdapter.this.addAll();
CustomBasketAdapter.this.notifyDataSetChanged();
By
CustomBasketAdapter.this.remove(item);
CustomBasketAdapter.this.notifyDataSetChanged();
Nevermind I found the solution
what i've done is called the method that builds the list
from within the custom adapter
if(context instanceof ViewBasket){
((ViewBasket)context).GetBasketProducts();
}
because deleting the item only changed the data on the database which passes me the information i needed to request the information again