ListView Not Displaying in New Activity - java

I am trying to get a ListView to appear in a new activity. I can see the record ID in the logcat, and I can see that the proper ID is being selected in debug view, but when I go to the new activity the list array is empty.
This is what I am seeing in debug view:
In the logcat I see this:
2018-10-07 11:39:09.286 12624-12624/ca.rvogl.tpbcui D/SAVEDLEAGUEID_VAL: 1
2018-10-07 11:39:09.286 12624-12624/ca.rvogl.tpbcui D/LEAGUEID_VAL: android.support.v7.widget.AppCompatTextView{e67a170 G.ED..... ......I. 0,0-0,0 #7f080112 app:id/tvLeagueId}
2018-10-07 11:39:09.293 12624-12624/ca.rvogl.tpbcui D/GETALLBOWLERS-SQL: SQL used = >>>>SELECT * FROM bowlers WHERE league_id = '1' ORDER BY timestamp DESC<<<<
2018-10-07 11:39:09.298 12624-12624/ca.rvogl.tpbcui D/GETALLBOWLERS-CNT: Number of rows retrieved = 0
2018-10-07 11:39:09.299 12624-12624/ca.rvogl.tpbcui D/GETALLBOWLERS-CNT: Number of elements in bowlerslist = 0
As you can see from the logcat the savedLeagueId is being passed to the SQLite Query that is suppose to be getting the list of Bowlers for the listview. However the number of elements in the bowlerslist is 0.
I have gone through the code over and over again but I am unable to isolate where the issue is.
LeagueAdapter.java
public class LeagueAdapter extends RecyclerView.Adapter<LeagueAdapter.MyViewHolder> {
private Context context;
private List<League> leaguesList;
public void notifyDatasetChanged(List<League> newleagueslist) {
leaguesList.clear();
leaguesList.addAll(newleagueslist);
super.notifyDataSetChanged();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView basescore;
public TextView basescorepercentage;
public TextView id;
public TextView wins;
public TextView losses;
public TextView timestamp;
public TextView buttonViewOption;
public MyViewHolder(View view) {
super(view);
id = view.findViewById( R.id.tvLeagueId);
name = view.findViewById(R.id.tvSeriesName );
basescore = view.findViewById(R.id.tvBaseScore );
basescorepercentage = view.findViewById(R.id.tvBaseScorePercentage );
wins = view.findViewById(R.id.tvLeagueWins );
losses = view.findViewById(R.id.tvLeagueLosses );
timestamp = view.findViewById(R.id.timestamp);
buttonViewOption = (TextView) view.findViewById(R.id.buttonViewOptions);
}
}
public LeagueAdapter(Context context, List<League> leaguesList) {
this.context = context;
this.leaguesList = leaguesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.listview_league, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
League league = leaguesList.get(position);
int id = league.getId();
Log.d("id", String.valueOf(id));
int leagueId = id;
Log.d("leagueId", String.valueOf(leagueId));
holder.id.setText(String.valueOf(leagueId));
holder.name.setText(league.getName());
holder.basescore.setText(league.getBaseScore());
holder.basescorepercentage.setText(league.getBaseScorePercentage());
holder.wins.setText(league.getWins());
holder.losses.setText(league.getLosses());
/*if (league.getAverage() != "") {
holder.leagueAverage.setText(String.format("League Avg: %s", league.getAverage()));
} else {
holder.leagueAverage.setText(String.format("League Avg: %s", "0"));
}*/
//Formatting And Displaying Timestamp
holder.timestamp.setText(formatDate(league.getTimestamp()));
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(context, holder.buttonViewOption);
//inflating menu from xml resource
popup.inflate(R.menu.league_options_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.profile:
Log.d("leagueId", String.valueOf(position));
int leagueId = league.getId();
String savedLeagueId = String.valueOf(id);
Intent myIntent = new Intent(context, LeagueProfileViewActivity.class);
myIntent.putExtra("leagueId", leagueId);
context.startActivity(myIntent);
break;
case R.id.delete:
((MainActivity) context).deleteLeague(position);
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//String leagueId = String.valueOf(leaguesList.get(position).getId());
int leagueId = league.getId();
String savedLeagueId = String.valueOf(id);
Log.d("leagueId", String.valueOf(position));
Intent myIntent = new Intent(context, BowlerActivity.class);
myIntent.putExtra("leagueId", savedLeagueId);
context.startActivity(myIntent);
}
});
}
#Override
public int getItemCount() {
return leaguesList.size();
}
//Formatting TimeStamp to 'EEE MMM dd yyyy (HH:mm:ss)'
//Input : 2018-05-23 9:59:01
//Output : Wed May 23 2018 (9:59:01)
private String formatDate(String dateStr) {
try {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = fmt.parse(dateStr);
SimpleDateFormat fmtOut = new SimpleDateFormat("EEE MMM dd yyyy (HH:mm:ss)");
return fmtOut.format(date);
} catch (ParseException e) {
}
return "";
}
}
I am moving to the BowlerActivity using holder.name, where I am passing the League ID using an intent.
BowlerActivity.java
public class BowlerActivity extends AppCompatActivity {
private BowlerAdapter mAdapter;
private final List<Bowler> bowlersList = new ArrayList<>();
private TextView noBowlersView;
private DatabaseHelper db;
private TextView leagueId;
private String savedLeagueId;
/*private TextView seriesleagueId;
private String seriesLeagueId;
private TextView bowlerAverage;
private TextView bowlerHandicap;
private String savedBowlerAverage;*/
private static final String PREFS_NAME = "prefs";
private static final String PREF_BLUE_THEME = "blue_theme";
private static final String PREF_GREEN_THEME = "green_theme";
private static final String PREF_ORANGE_THEME = "purple_theme";
private static final String PREF_RED_THEME = "red_theme";
private static final String PREF_YELLOW_THEME = "yellow_theme";
#Override protected void onResume() {
super.onResume();
db = new DatabaseHelper( this );
mAdapter.notifyDatasetChanged( db.getAllBowlers(savedLeagueId ) );
}
#Override
protected void onCreate(Bundle savedInstanceState) {
//Use Chosen Theme
SharedPreferences preferences = getSharedPreferences( PREFS_NAME, MODE_PRIVATE );
boolean useBlueTheme = preferences.getBoolean( PREF_BLUE_THEME, false );
if (useBlueTheme) {
setTheme( R.style.AppTheme_Blue_NoActionBar );
}
boolean useGreenTheme = preferences.getBoolean( PREF_GREEN_THEME, false );
if (useGreenTheme) {
setTheme( R.style.AppTheme_Green_NoActionBar );
}
boolean useOrangeTheme = preferences.getBoolean( PREF_ORANGE_THEME, false );
if (useOrangeTheme) {
setTheme( R.style.AppTheme_Orange_NoActionBar );
}
boolean useRedTheme = preferences.getBoolean( PREF_RED_THEME, false );
if (useRedTheme) {
setTheme( R.style.AppTheme_Red_NoActionBar );
}
boolean useYellowTheme = preferences.getBoolean( PREF_YELLOW_THEME, false );
if (useYellowTheme) {
setTheme( R.style.AppTheme_Yellow_NoActionBar );
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bowler);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull( getSupportActionBar() ).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
overridePendingTransition(0, 0);
}
});
savedLeagueId = String.valueOf(getIntent().getStringExtra("leagueId"));
leagueId = findViewById(R.id.tvLeagueId);
Log.d("SAVEDLEAGUEID_VAL", String.valueOf(savedLeagueId));
Log.d("LEAGUEID_VAL", String.valueOf(leagueId));
/*bowlerAverage = (TextView) findViewById(R.id.tvBowlerAverage);
bowlerHandicap = (TextView) findViewById(R.id.tvBowlerHandicap);*/
CoordinatorLayout coordinatorLayout = findViewById( R.id.coordinator_layout );
RecyclerView recyclerView = findViewById( R.id.recycler_view );
noBowlersView = findViewById(R.id.empty_bowlers_view);
db = new DatabaseHelper(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_bowler_fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//showBowlerDialog(false, null, -1);
boolean shouldUpdate = false;
int bowlerId = -1;
String leagueId = String.valueOf(savedLeagueId);
Intent intent = new Intent(getApplicationContext(), BowlerProfileEditActivity.class);
intent.putExtra("shouldUpdate", shouldUpdate);
intent.putExtra("leagueId", leagueId);
intent.putExtra("bowlerId", bowlerId);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
}
});
mAdapter = new BowlerAdapter(this, bowlersList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
toggleEmptyBowlers();
}
//Inserting New Bowler In The Database And Refreshing The List
private void createBowler(String leagueId, String bowlerName) {
String bowlerAverage = "0";
//Inserting Bowler In The Database And Getting Newly Inserted Bowler Id
long id = db.insertBowler(savedLeagueId, bowlerName, bowlerAverage);
//Get The Newly Inserted Bowler From The Database
Bowler n = db.getBowler(savedLeagueId);
if (n != null) {
//Adding New Bowler To The Array List At Position 0
bowlersList.add( 0, n );
//Refreshing The List
mAdapter.notifyDatasetChanged(db.getAllBowlers(savedLeagueId));
//mAdapter.notifyDataSetChanged();
toggleEmptyBowlers();
}
}
//Updating Bowler In The Database And Updating The Item In The List By Its Position
private void updateBowler(String bowlerName, int position) {
Bowler n = bowlersList.get(position);
//Updating Bowler Text
n.setLeagueId(savedLeagueId);
n.setName(bowlerName);
//Updating The Bowler In The Database
db.updateBowler(n);
//Refreshing The List
bowlersList.set(position, n);
mAdapter.notifyItemChanged(position);
toggleEmptyBowlers();
}
//Deleting Bowler From SQLite Database And Removing The Bowler Item From The List By Its Position
public void deleteBowler(int position) {
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Series will be deleted.", Snackbar.LENGTH_LONG)
.setActionTextColor(Color.YELLOW)
.setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View v) {
//Deleting The Bowler From The Database
db.deleteBowler(bowlersList.get(position));
//Removing The Bowler From The List
bowlersList.remove(position);
mAdapter.notifyItemRemoved(position);
//db.leagueAverageScore(savedLeagueId);
toggleEmptyBowlers();
}
});
snackbar.show();
}
//Toggling List And Empty Bowler View
private void toggleEmptyBowlers() {
//You Can Check bowlerList.size() > 0
if (db.getBowlersCount() > 0) {
noBowlersView.setVisibility( View.GONE);
} else {
noBowlersView.setVisibility( View.VISIBLE);
}
}
#Override
public void onRestart() {
super.onRestart();
//When BACK BUTTON is pressed, the activity on the stack is restarted
//Do what you want on the refresh procedure here
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate( R.menu.menu_main, menu );
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
overridePendingTransition(0, 0);
return true;
}
return super.onOptionsItemSelected( item );
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
//Check If Request Code Is The Same As What Is Passed - Here It Is 1
if(requestCode==1)
{
String savedLeagueId=data.getStringExtra("seriesLeagueId");
String seriesBowlerId=data.getStringExtra("seriesBowlerId");
bowlersList.addAll(db.getAllBowlers(savedLeagueId));
}
}
#Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
overridePendingTransition(0, 0);
}
}
Bowler Methods in DatabaseHelper.java
public long insertBowler(String leagueId, String bowlerName, String bowlerAverage) {
String bowlerHandicap ="0";
//Get Writable Database That We Want To Write Data Too
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//`id` and `timestamp` Will Be Inserted Automatically
values.put(Bowler.COLUMN_LEAGUE_ID, leagueId);
values.put(Bowler.COLUMN_NAME, bowlerName);
values.put(Bowler.COLUMN_BOWLER_AVERAGE, bowlerAverage);
values.put(Bowler.COLUMN_BOWLER_HANDICAP, bowlerHandicap);
//Insert Row
//long id = db.insert(Bowler.TABLE_NAME, null, values);
long id = db.insertOrThrow( Bowler.TABLE_NAME, null, values );
Log.d("INSERTBOWLER","Number of bowlers in db = " + String.valueOf( DatabaseUtils.queryNumEntries(db,Bowler.TABLE_NAME)));
//Close Database Connection
db.close();
//Return Newly Inserted Row Id
return id;
}
public Bowler getBowler(String leagueId) {
//Get Readable Database If We Are Not Inserting Anything
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query( Bowler.TABLE_NAME,
new String[]{Bowler.COLUMN_ID, Bowler.COLUMN_LEAGUE_ID, Bowler.COLUMN_NAME, Bowler.COLUMN_BOWLER_AVERAGE, Bowler.COLUMN_BOWLER_HANDICAP, Bowler.COLUMN_TIMESTAMP},
Bowler.COLUMN_LEAGUE_ID + "=?",
new String[]{String.valueOf(leagueId)}, null, null, null, null);
Bowler bowler = null;
if (cursor.moveToFirst()) {
//Prepare Bowler Object
bowler = new Bowler(
cursor.getInt(cursor.getColumnIndex(Bowler.COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_NAME)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_BOWLER_AVERAGE)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_BOWLER_HANDICAP)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));
//Close Database Connection
cursor.close();
return bowler;
} else {
return bowler;
}
}
public List<Bowler> getAllBowlers(String leagueId) {
List<Bowler> bowlers = new ArrayList<>();
//Select All Query
String selectQuery = "SELECT * FROM " + Bowler.TABLE_NAME + " WHERE " + Bowler.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " ORDER BY " +
Bowler.COLUMN_TIMESTAMP + " DESC";
Log.d("GETALLBOWLERS-SQL","SQL used = >>>>" +selectQuery + "<<<<");
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
Log.d("GETALLBOWLERS-CNT","Number of rows retrieved = " + String.valueOf(cursor.getCount()));
//Looping Through All Rows And Adding To The List
if (cursor.moveToFirst()) {
do {
Bowler bowler = new Bowler();
bowler.setId(cursor.getInt(cursor.getColumnIndex(Bowler.COLUMN_ID)));
bowler.setLeagueId(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)));
bowler.setName(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_NAME)));
bowler.setAverage(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_BOWLER_AVERAGE)));
bowler.setHandicap(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_BOWLER_HANDICAP)));
bowler.setTimestamp(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));
bowlers.add(bowler);
} while (cursor.moveToNext());
}
cursor.close();
//Close Database Connection
db.close();
Log.d("GETALLBOWLERS-CNT","Number of elements in bowlerslist = " + String.valueOf(bowlers.size()));
//Return Bowlers List
return bowlers;
}
public int getBowlersCount() {
String countQuery = "SELECT * FROM " + Bowler.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
//Return The Count
return count;
}
public int updateBowler(Bowler bowler) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Bowler.COLUMN_LEAGUE_ID, bowler.getLeagueId());
values.put(Bowler.COLUMN_NAME, bowler.getName());
values.put(Bowler.COLUMN_BOWLER_AVERAGE, bowler.getAverage());
//Updating Row
return db.update(Bowler.TABLE_NAME, values, Bowler.COLUMN_ID + " = ?",
new String[]{String.valueOf(bowler.getId())});
}
public void deleteBowler(Bowler bowler) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete( Bowler.TABLE_NAME, Bowler.COLUMN_ID + " = ?",
new String[]{String.valueOf( bowler.getId())});
db.close();
}
I am hoping that someone will be able to point out what I am doing incorrectly in order to fix this issue.
If any additional information is need please let me know and I will post it.

I have figured out why all my new bowler entries have an id of 2. In my edit Bowler Profile Activity I have the following : leagueId = String.valueOf(getIntent().getIntExtra("leagueId",2)); The default value is 2 and because I was not grabbing the information being passed to the new Activity in the proper manner the app was always using 2 as the BowlerId.
I changed the code that was capturing the information from the intent to the following:
Intent intent = getIntent();
leagueId = intent.getStringExtra("leagueId");
With this change I was able to capture all the bowlers that belong to a particular league. I only realized that I was passing the information incorrectly after reading through the following post:
Pass a String from one Activity to another Activity in Android

Related

RecyclerView not updating after creating or deleting playlists in Fragments

I am trying to update my recyclerView by notifyDataSetChanged(). But it's not working. I have to close my specific fragment and open it to see the changes.
This is MyFragment where I call recyclerView
BottomSheetFragment.java
// showing Playlist Names
recyclerPlayListViewName =
bottomView.findViewById(R.id.recycler_play_list_view_name);
playlists = new ArrayList<Playlist>();
PlayListMethodHolder.getplaylistList(getContext(), playlists);
playlistAdapter = new PlaylistAdapter(bottomView.getContext(), playlists,
"bottomsheet");
recyclerPlayListViewName.setHasFixedSize(true);
recyclerPlayListViewName.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerPlayListViewName.setAdapter(playlistAdapter);
playlistAdapter.notifyDataSetChanged();
This is AdapterClass where I call to delete the playlist method.
PlaylistAdapter.java
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
long plistID = playlists.get(position).getId();
switch (item.getItemId()) {
case R.id.pPlay:
break;
case R.id.pRename:
String dpType = "playlistRename";
PlayListPopDialog popDialog = new PlayListPopDialog(mContext,
dpType, plistID, playlists);
popDialog.show();
break;
case R.id.pDelete:
PlayListMethodHolder.deletePlaylist(mContext, plistID);
break;
And This is another DialogView where I call Create PlayList
PlayListPopDialog.java
findViewById(R.id.btn_playlist_save).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtCreateNamePlaylist = findViewById(R.id.edt_create_name_playlist);
String playlistName = edtCreateNamePlaylist.getText().toString().trim();
if (!(playlistName.isEmpty())) {
boolean state = PlayListMethodHolder
.doPlaylistExists(getContext(), playlistName);
if (!state) {
PlayListMethodHolder.createPlaylist(getContext(), playlistName);
dismiss();
} else {
Toast.makeText(getContext(), "This name is already exists.",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getContext(), "Empty name", Toast.LENGTH_SHORT).show();
}
}
});
Finally, this is a class for holding all methods of creating or deleting PlayLists
PlayListMethodHolder.java
public class PlayListMethodHolder {
public static void createPlaylist(Context context, String playlistName) {
String[] projectionName = new String [] {
MediaStore.Audio.Playlists._ID,
MediaStore.Audio.Playlists.NAME,
MediaStore.Audio.Playlists.DATA,
};
ContentValues nameValues = new ContentValues();
nameValues.put(MediaStore.Audio.Playlists.NAME, playlistName);
nameValues.put(MediaStore.Audio.Playlists.DATE_ADDED,
System.currentTimeMillis());
nameValues.put(MediaStore.Audio.Playlists.DATE_MODIFIED,
System.currentTimeMillis());
Uri uri = context.getApplicationContext().getContentResolver()
.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, nameValues);
if (uri != null) {
context.getApplicationContext().getContentResolver()
.query(uri, projectionName, null, null, null);
context.getApplicationContext().getContentResolver().notifyChange(uri, null);
}
}
// Delete single playlist from list
public static void deletePlaylist (#NonNull final Context context, long playlistId){
String playlistid = String.valueOf(playlistId);
ContentResolver resolver = context.getContentResolver();
String where = MediaStore.Audio.Playlists._ID + "=?";
String[] whereVal = {playlistid};
resolver.delete(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, where,
whereVal);
return ;
}
// get Playlist names
public static void getplaylistList(Context context, ArrayList<Playlist> plist) {
Cursor playlistCursor = context.getContentResolver().query(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
null,
null,
null,
null);
if (playlistCursor != null && playlistCursor.moveToFirst()) {
//get columns
int idColumn = playlistCursor.getColumnIndex
(MediaStore.Audio.Playlists._ID);
int titleColumn = playlistCursor.getColumnIndex
(MediaStore.Audio.Playlists.NAME);
do {
long thisId = playlistCursor.getLong(idColumn);
String thisTitle = playlistCursor.getString(titleColumn);
plist.add(new Playlist(thisId, thisTitle));
} while (playlistCursor.moveToNext());
}
}
Tap to see PlayList Design View

null value on variable passed from inside a onclick response

Is there any reason why method CreatePlan won't allow me access to variable recipe_name from the onRecipeClicked function which is retrieved from the recyclerview adapter. The Log shows that the value is retrieved from the recyclerview, but I can't seem to pass it to another method.
Any help is appreciated.
Update
Also is there a way of assigning the auto incremented id created from createPlanRecipe to the id variable in createPlan?
public class CreateMealPlan extends MainActivity {
DatePicker datepicker;
Button submit;
List<com.stu54259.plan2cook.Model.Category> listRecipe = new ArrayList<>();
Cursor c;
RecyclerView recipeList;
RecipeListAdapter adapterRecipe;
String recipe_name;
EditText editPlanName;
Integer id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_meal_plan);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(CreateMealPlan.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(CreateMealPlan.this,RecipeSearch.class);
startActivity(b);
break;
/*case R.id.shoppingList:
Intent c = new Intent(CreateMealPlan.this, ShoppingList.class);
startActivity(c);
break;*/
case R.id.mealPlan:
Intent d = new Intent(CreateMealPlan.this, MenuPlan.class);
startActivity(d);
break;
/*case R.id.reminder:
Intent e = new Intent(CreateMealPlan.this, Reminder.class);
startActivity(e);
break*/
}
return false;
}
});
datepicker = findViewById(R.id.calendarView);
ListRecipes();
RecipeListAdapter.OnRecipeClickListener listener = new RecipeListAdapter.OnRecipeClickListener() {
public void onRecipeClicked(int position, String recipe_name) {
Log.d("Recipe selected", recipe_name);
}
};
adapterRecipe = new RecipeListAdapter(this, listRecipe, listener);
recipeList = findViewById(R.id.recipes);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
recipeList.setLayoutManager(mLayoutManager);
recipeList.setItemAnimator(new DefaultItemAnimator());
recipeList.setAdapter(adapterRecipe);
submit = (Button) findViewById(R.id.create);
// perform click event on submit button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreatePlan();
}
});
}
public void ListRecipes() {
listRecipe.clear();
SQLiteDatabase db = (new DatabaseManager(this).getWritableDatabase());
String selectQuery = " SELECT recipe_name, image, image2, category" + " FROM " + DatabaseManager.TABLE_RECIPE + " GROUP BY recipe_name";
c = db.rawQuery(selectQuery, null);
Log.d("Query", selectQuery);
if (c.moveToFirst()) {
do {
com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
category.setRecipe_name(c.getString(c.getColumnIndex("recipe_name")));
category.setImage(c.getInt(c.getColumnIndex("image")));
category.setImage2(c.getString(c.getColumnIndex("image2")));
category.setCategory_name(c.getString(c.getColumnIndex("category")));
listRecipe.add(category);
} while (c.moveToNext());
c.close();
}
}
public void CreatePlan(){
editPlanName = findViewById(R.id.editPlanName);
String plan_name = editPlanName.getText().toString();
DatabaseManager db;
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Integer d_name = day;
Log.d("Date", String.valueOf(d_name));
String dayOfTheWeek = sdf.format(d_name);
String date = day + "/" + month + "/" +year;
db = new DatabaseManager(getApplicationContext());
db.createPlanRecipe(d_name, dayOfTheWeek, recipe_name);
db.createPlan(plan_name, id);
}
}

Cannot Figure Out Why Intent is not Being Passed Back to Previous Activity

I have been trying to track down why my LeagueId is not being passed back to the previous activity for sometime now and I cannot seem to figure it out. I have gone through many different posts looking for ideas on how to fix the issue and I cannot seem to find anything that could be relevant.
I am trying to pass the LeagueId back to a listview in order to show the list of Series for a specific bowler and league. I am passing the BowlerId back but not the LeagueId. When I debug the app I can see that the variable that is supposed to be passed back with intent is populated, but when it goes back to the previous activity it is not being picked up.
This is the code that sets the intent:
//View Series Summary Cancel Button
final Button cancel_button = (Button) findViewById(R.id.sCancel);
cancel_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SeriesActivity.class);
intent.putExtra("leagueId", savedLeagueId);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
}
});
This is my code for the previous activity:
public class SeriesActivity extends AppCompatActivity {
private SeriesAdapter mAdapter;
private final List<Series> seriesList = new ArrayList<>();
private TextView noSeriesView;
private DatabaseHelper db;
private TextView leagueId;
private String savedLeagueId;
private TextView bowlerId;
private String savedBowlerId;
private TextView seriesId;
private String savedSeriesId;
private TextView seriesAverage;
private String savedSeriesAverage;
private static final String PREFS_NAME = "prefs";
private static final String PREF_BLUE_THEME = "blue_theme";
private static final String PREF_GREEN_THEME = "green_theme";
private static final String PREF_ORANGE_THEME = "purple_theme";
private static final String PREF_RED_THEME = "red_theme";
private static final String PREF_YELLOW_THEME = "yellow_theme";
#Override protected void onResume() {
super.onResume();
db = new DatabaseHelper( this );
mAdapter.notifyDatasetChanged( db.getAllSeries( savedLeagueId, savedBowlerId ) );
}
#Override
protected void onCreate(Bundle savedInstanceState) {
//Use Chosen Theme
SharedPreferences preferences = getSharedPreferences( PREFS_NAME, MODE_PRIVATE );
boolean useBlueTheme = preferences.getBoolean( PREF_BLUE_THEME, false );
if (useBlueTheme) {
setTheme( R.style.AppTheme_Blue_NoActionBar );
}
boolean useGreenTheme = preferences.getBoolean( PREF_GREEN_THEME, false );
if (useGreenTheme) {
setTheme( R.style.AppTheme_Green_NoActionBar );
}
boolean useOrangeTheme = preferences.getBoolean( PREF_ORANGE_THEME, false );
if (useOrangeTheme) {
setTheme( R.style.AppTheme_Orange_NoActionBar );
}
boolean useRedTheme = preferences.getBoolean( PREF_RED_THEME, false );
if (useRedTheme) {
setTheme( R.style.AppTheme_Red_NoActionBar );
}
boolean useYellowTheme = preferences.getBoolean( PREF_YELLOW_THEME, false );
if (useYellowTheme) {
setTheme(R.style.AppTheme_Yellow_NoActionBar);
}
super.onCreate(savedInstanceState);
super.onResume();
setContentView(R.layout.activity_series);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar( toolbar );
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String seriesLeagueId = String.valueOf( getIntent().getStringExtra( "savedLeagueId" ) );
String seriesBowlerId = String.valueOf( getIntent().getIntExtra( "seriesBowlerId", 2 ) );
Intent intent=new Intent();
intent.putExtra("savedLeagueId",seriesLeagueId);
intent.putExtra("seriesBowlerId",seriesBowlerId);
setResult(1,intent);
finish();//finishing activity
overridePendingTransition(0, 0);
}
});
Intent intent = getIntent();
//savedLeagueId = String.valueOf( getIntent().getStringExtra( "savedLeagueId" ) );
savedLeagueId = intent.getStringExtra("savedLeagueId");
leagueId = (TextView) findViewById( R.id.tvLeagueId );
savedBowlerId = String.valueOf( getIntent().getIntExtra( "seriesBowlerId", 2 ) );
bowlerId = (TextView) findViewById( R.id.tvBowlerId );
savedSeriesId = String.valueOf( getIntent().getIntExtra( "seriesId", 3 ) );
seriesId = (TextView) findViewById( R.id.tvSeriesId );
seriesAverage = (TextView) findViewById(R.id.tvSeriesAverage);
CoordinatorLayout coordinatorLayout = findViewById( R.id.coordinator_layout );
RecyclerView recyclerView = findViewById( R.id.recycler_view );
noSeriesView = findViewById( R.id.empty_series_view );
db = new DatabaseHelper( this );
db.bowlerAverageScore(savedLeagueId, savedBowlerId);
FloatingActionButton fab = (FloatingActionButton) findViewById( R.id.add_series_fab );
fab.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
showSeriesDialog( false, null, -1 );
}
} );
mAdapter = new SeriesAdapter( this, seriesList );
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager( getApplicationContext() );
recyclerView.setLayoutManager( mLayoutManager );
recyclerView.setItemAnimator( new DefaultItemAnimator() );
recyclerView.setAdapter( mAdapter );
toggleEmptySeries();
}
//Inserting New Series In The Database And Refreshing The List
private void createSeries(String leagueId, String bowlerId, String series) {
//Inserting Series In The Database And Getting Newly Inserted Series Id
String seriesAverage = "0";
String seriesLow = "0";
String seriesHigh = "0";
long id = db.insertSeries( leagueId, bowlerId, series, seriesAverage, seriesLow, seriesHigh );
//Get The Newly Inserted Series From The Database
Series n = db.getSeries( leagueId, bowlerId );
if (n != null) {
//Adding New Series To The Array List At Position 0
seriesList.add( 0, n );
//Refreshing The List
mAdapter.notifyDatasetChanged( db.getAllSeries( savedLeagueId, savedBowlerId ) );
toggleEmptySeries();
}
}
//Updating Series In The Database And Updating The Item In The List By Its Position
private void updateSeries(String name, int position) {
Series n = seriesList.get( position );
//Updating Series Text
n.setLeagueId( savedLeagueId );
n.setBowlerId( savedBowlerId );
n.setName( name );
//Updating The Series In The Database
db.updateSeries( n );
//Refreshing The List
seriesList.set( position, n );
//mAdapter.notifyItemChanged(position);
mAdapter.notifyDatasetChanged( db.getAllSeries( savedLeagueId, savedBowlerId ) );
toggleEmptySeries();
}
//Deleting Series From SQLite Database And Removing The Bowler Item From The List By Its Position
public void deleteSeries(int position) {
//Deleting The Series From The Database
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Series will be deleted.", Snackbar.LENGTH_LONG)
.setActionTextColor(Color.YELLOW)
.setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View v) {
db.deleteSeries( seriesList.get( position ) );
seriesList.remove( position );
mAdapter.notifyItemRemoved( position );
toggleEmptySeries();
}
});
snackbar.show();
}
//Show Alert Dialog With Pie Chart Displaying Stats
public void showSeriesDetailsDialog( final Series series, final int position) {
int seriesId = seriesList.get( position ).getId();
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
final View view = View.inflate(this, R.layout.dialog_seriesdetails, null);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(new ContextThemeWrapper(SeriesActivity.this, R.style.AppTheme));
alertDialogBuilderUserInput.setView(view);
TextView dialogTitle = view.findViewById(R.id.SeriesStatisticsDialog);
dialogTitle.setText("Series Summary");
String savedSeriesId = String.valueOf(seriesId);
TextView highScore = (TextView) view.findViewById(R.id.tvSeriesHigh);
String highString = db.seriesHighScore(savedLeagueId, savedBowlerId, savedSeriesId);
TextView lowScore = (TextView) view.findViewById(R.id.tvSeriesLow);
String lowString = db.seriesLowScore(savedLeagueId, savedBowlerId, savedSeriesId);
TextView averageScore = (TextView) view.findViewById(R.id.tvSeriesAverage);
String averageString = db.seriesAverageScore(savedLeagueId, savedBowlerId, savedSeriesId);
TextView seriesScratch = (TextView) view.findViewById(R.id.tvSeriesScratch);
String scratchString = db.seriesScratch(savedLeagueId, savedBowlerId, savedSeriesId);
Integer strikes = db.seriesTotalStrikes(savedLeagueId, savedBowlerId, savedSeriesId);
Integer spares = db.seriesTotalSpares(savedLeagueId, savedBowlerId, savedSeriesId);
Integer splits = db.seriesTotalSplits(savedLeagueId, savedBowlerId, savedSeriesId);
Integer splitconversion = db.seriesTotalSplitConversions(savedLeagueId, savedBowlerId, savedSeriesId);
Integer openframes = db.seriesTotalOpenFrames(savedLeagueId, savedBowlerId, savedSeriesId);
PieChart pieChart = (PieChart) view.findViewById(R.id.chart);
ArrayList<Entry> yvalues = new ArrayList<Entry>();
if (strikes < 1) {
} else {
yvalues.add(new Entry(strikes, 0));
}
if (spares < 1) {
} else {
yvalues.add(new Entry(spares, 1));
}
if (splits < 1) {
} else {
yvalues.add(new Entry(splits, 2));
}
if (splitconversion < 1) {
} else {
yvalues.add(new Entry(splitconversion, 3));
}
if (openframes < 1) {
} else {
yvalues.add(new Entry(openframes, 4));
}
PieDataSet dataSetPie = new PieDataSet(yvalues, "");
ArrayList<String> xValues = new ArrayList<String>();
if (strikes < 1) {
} else {
xValues.add("Strikes");
}
if (spares < 1) {
} else {
xValues.add("Spares");
}
if (splits < 1) {
} else {
xValues.add("Splits");
}
if (splitconversion < 1) {
} else {
xValues.add("Split Conversions");
}
if (openframes < 1) {
} else {
xValues.add("Open Frames");
}
if (strikes == 0 && spares == 0 && splits == 0 && splitconversion == 0 && openframes == 0) {
pieChart.setDrawHoleEnabled(false);
pieChart.setNoDataText("No Pin Data Available!");
} else {
PieData data = new PieData(xValues, dataSetPie);
data.setValueFormatter(new SeriesActivity.DecimalRemover(new DecimalFormat("###,###,###")));
dataSetPie.setColors(ColorTemplate.COLORFUL_COLORS);
data.setValueTextSize(10f);
data.setValueTextColor(Color.DKGRAY);
pieChart.setDrawHoleEnabled(true);
pieChart.setData(data);
pieChart.setDescription("Series Results");
pieChart.setTransparentCircleAlpha(110);
pieChart.setTransparentCircleRadius(55f);
pieChart.setHoleRadius(50f);
pieChart.animateXY(2000, 2000);
Legend legend = pieChart.getLegend();
legend.setWordWrapEnabled(true);
legend.setPosition(BELOW_CHART_CENTER);
legend.setForm(CIRCLE);
}
TextView seriesScoreOverview = (TextView) view.findViewById(R.id.tvSeriesScoreOverviewTitle);
seriesScoreOverview.setText("Series Scores Overview");
ArrayList<BarEntry> yVals = new ArrayList<BarEntry>();
for (int i = 0; i < db.queryYData(savedLeagueId, savedBowlerId, savedSeriesId).size(); i++)
yVals.add(new BarEntry(db.queryYData(savedLeagueId, savedBowlerId, savedSeriesId).get(i), i));
ArrayList<String> xVals = new ArrayList<String>();
for (int i = 0; i < db.queryXData(savedLeagueId, savedBowlerId, savedSeriesId).size(); i++)
xVals.add(db.queryXData(savedLeagueId, savedBowlerId, savedSeriesId).get(i));
BarChart barChart = (BarChart) view.findViewById(R.id.chart1);
BarDataSet dataSet = new BarDataSet(yVals, "Series Score Values");
dataSet.setColors(ColorTemplate.COLORFUL_COLORS);
BarData dataBarChart = new BarData(xVals, dataSet);
//LimitLine line = new LimitLine(12f, "Series Scores");
//line.setTextSize(12f);
//line.setLineWidth(4f);
YAxis leftAxis = barChart.getAxisLeft();
//leftAxis.addLimitLine(line);
barChart.setData(dataBarChart);
barChart.setDescription("Series Scores");
barChart.animateY(2000);
barChart.setBackgroundColor(getResources().getColor(android.R.color.white)); // use your bg color
barChart.setDescription(" ");
barChart.setDrawGridBackground(false);
barChart.setDrawBorders(false);
barChart.getAxisLeft().setDrawLabels(true);
barChart.getAxisRight().setDrawLabels(false);
barChart.getXAxis().setDrawLabels(false);
barChart.getAxisLeft().setDrawGridLines(false);
barChart.getXAxis().setDrawGridLines(false);
barChart.getAxisRight().setDrawGridLines(false);
barChart.setDrawGridBackground(false);
Legend legendBarChart = barChart.getLegend();
legendBarChart.setEnabled(false);
alertDialogBuilderUserInput.setCancelable( false ).setPositiveButton( "ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
} );
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
highScore.setText("Scratch High: " + highString);
lowScore.setText("Scratch Low: " + lowString);
averageScore.setText("Series Average: " + averageString);
seriesScratch.setText("Total Series Scratch: " + scratchString);
db.bowlerAverageScore(savedLeagueId, savedBowlerId);
}
//Show Alert Dialog With EditText Options to Enter/Edit A Series
//When shouldUpdate = true, It Will Automatically Display Old Series Name And Change The Button Text To UPDATE
public void showSeriesDialog(final boolean shouldUpdate, final Series series, final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from( getApplicationContext() );
final View view = View.inflate( this, R.layout.dialog_series, null );
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder( SeriesActivity.this );
alertDialogBuilderUserInput.setView( view );
final EditText inputSeries = view.findViewById( R.id.etSeriesNameInput );
leagueId.setText( savedLeagueId );
bowlerId.setText( savedBowlerId );
TextView dialogTitle = view.findViewById( R.id.dialog_title );
dialogTitle.setText( !shouldUpdate ? getString( R.string.lbl_new_series_title ) : getString( R.string.lbl_edit_series_title ) );
if (shouldUpdate && series != null) {
inputSeries.setText( series.getName() );
leagueId.setText( series.getLeagueId() );
bowlerId.setText( series.getBowlerId() );
}
alertDialogBuilderUserInput.setCancelable( false ).setPositiveButton( shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
} ).setNegativeButton( "cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
dialogBox.cancel();
}
} ) .setNeutralButton("use date",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
String dateNow = getDateNow();
inputSeries.setText(dateNow);
}
});
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.white);
alertDialog.getButton( AlertDialog.BUTTON_NEUTRAL ).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
//Show Toast Message When No Text Is Entered
if (inputSeries.getText().toString() !=null || !inputSeries.getText().toString().isEmpty() ) {
String dateNow = getDateNow();
inputSeries.setText(dateNow);
return;
} else {
alertDialog.dismiss();
}
//Check If User Is Updating Series
if (shouldUpdate && series != null) {
//Updating Series By Its Id
updateSeries( inputSeries.getText().toString(), position );
} else {
//Creating New Series
createSeries( leagueId.getText().toString(), bowlerId.getText().toString(), inputSeries.getText().toString() );
}
}
} );
alertDialog.getButton( AlertDialog.BUTTON_POSITIVE ).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
//Show Toast Message When No Text Is Entered
if (TextUtils.isEmpty( inputSeries.getText().toString() )) {
Toast.makeText( SeriesActivity.this, "Enter Series!", Toast.LENGTH_SHORT ).show();
return;
} else {
alertDialog.dismiss();
}
//Check If User Is Updating Series
if (shouldUpdate && series != null) {
//Updating Series By Its Id
updateSeries( inputSeries.getText().toString(), position );
} else {
//Creating New Series
createSeries( leagueId.getText().toString(), bowlerId.getText().toString(), inputSeries.getText().toString() );
}
}
} );
}
//Toggling List And Empty Series View
private void toggleEmptySeries() {
//You Can Check seriesList.size() > 0
if (db.getSeriesCount() > 0) {
noSeriesView.setVisibility( View.GONE );
} else {
noSeriesView.setVisibility( View.VISIBLE );
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate( R.menu.menu_main, menu );
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
overridePendingTransition(0, 0);
return true;
}
return super.onOptionsItemSelected( item );
}
#Override
public void onBackPressed() {
String seriesLeagueId = String.valueOf( getIntent().getStringExtra( "seriesLeagueId" ) );
String seriesBowlerId = String.valueOf( getIntent().getIntExtra( "seriesBowlerId", 2 ) );
Intent intent=new Intent();
intent.putExtra("seriesLeagueId",seriesLeagueId);
intent.putExtra("seriesBowlerId",seriesBowlerId);
setResult(1,intent);
finish();//finishing activity
overridePendingTransition(0, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
//Check If Request Code Is The Same As What Is Passed - Here It Is 1
if(requestCode==1)
{
String savedLeagueId=data.getStringExtra("seriesLeagueId");
String savedBowlerId=data.getStringExtra("seriesBowlerId");
seriesList.addAll( db.getAllSeries( savedLeagueId, savedBowlerId ) );
}
}
public class DecimalRemover extends PercentFormatter {
protected DecimalFormat mFormat;
public DecimalRemover(DecimalFormat format) {
this.mFormat = format;
}
#Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
//if(value < 10) return "";
return mFormat.format(value);
}
}
private String getDateNow() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE. MMM. dd, yyyy", Locale.ENGLISH);
return sdf.format(cal.getTime());
}
}
Any assistance with this would be greatly appreciated. If anything else is required please let me know and I would be more than happy to supply it.
This is my modified Cancel Button Code:
//View Series Summary Cancel Button
final Button cancel_button = (Button) findViewById(R.id.sCancel);
cancel_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SeriesActivity.class);
intent.putExtra("leagueId", savedLeagueId);
//startActivity(intent);
startActivityForResult(intent, 1);
finish();
overridePendingTransition(0, 0);
}
});
Image of Cancel Button:
Working Cancel Button Code:
//View Series Summary Cancel Button
final Button cancel_button = (Button) findViewById(R.id.sCancel);
cancel_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SeriesActivity.class);
Intent intent1 = intent.putExtra("seriesLeagueId", savedLeagueId);
startActivityForResult(intent, intent1, 1);
finish();
overridePendingTransition(0, 0);
}
});
}
private void startActivityForResult(Intent intent, Intent intent1, int i) {
}
Your SettingsActivity is not sending the leagueId to SeriesActivity#onActivityResult() because SeriesActivity has not requested a result when launching the SettingsActivity.
You should launch the SettingsActivity using startActivityForResult() instead of startActivity(). Afterwards you can return the result by setting it using setResult() in SettingsActivity. Please see here.
Note: You should not mess with Android's lifecycle -- you should not call super.onResume() in your onCreate().

ListView Not Refreshing When New Record Added

Can't seem to figure this out, I have gone through all the code without any success. When I add a new bowler to an empty list it appears correctly, when I add a second or more bowlers to the list, the name of the bowler shows up as the name of the first bowler added. I have included several screenshots below to show what I mean.
Obviously the order of these images goes left to right. I have include my BowlerActivity to this post as well. This is where I am creating and updating new and existing bowlers.
private BowlerAdapter mAdapter;
private List<Bowler> bowlersList = new ArrayList<>();
private CoordinatorLayout coordinatorLayout;
private RecyclerView recyclerView;
private TextView noBowlersView;
private DatabaseHelper db;
private TextView leagueId;
private String savedLeagueId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bowler);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
});
savedLeagueId = String.valueOf(getIntent().getIntExtra("leagueId",2));
leagueId = (TextView) findViewById(R.id.tvLeagueId);
coordinatorLayout = findViewById(R.id.coordinator_layout);
recyclerView = findViewById(R.id.recycler_view);
noBowlersView = findViewById(R.id.empty_bowlers_view);
db = new DatabaseHelper(this);
bowlersList.addAll(db.getAllBowlers(savedLeagueId));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_bowler_fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showBowlerDialog(false, null, -1);
}
});
mAdapter = new BowlerAdapter(this, bowlersList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
recyclerView.setAdapter(mAdapter);
toggleEmptyBowlers();
//On Long Click On The RecyclerView Item An Alert Dialog Is Opened With The Option To Choose Edit/Delete
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, final int position) {
String seriesLeagueId = bowlersList.get(position).getLeagueId();
int seriesBowlerId = bowlersList.get(position).getId();
Intent myIntent = new Intent(BowlerActivity.this, SeriesActivity.class);
myIntent.putExtra("seriesLeagueId", seriesLeagueId);
myIntent.putExtra("seriesBowlerId", seriesBowlerId);
startActivity(myIntent);
}
#Override
public void onLongClick(View view, int position) {
showActionsDialog(position);
}
}));
}
//Inserting New Bowler In The Database And Refreshing The List
private void createBowler(String leagueId, String bowlerName) {
//Inserting Bowler In The Database And Getting Newly Inserted Bowler Id
long id = db.insertBowler(leagueId, bowlerName);
//Get The Newly Inserted Bowler From The Database
Bowler n = db.getBowler(leagueId);
if (n != null) {
//Adding New Bowler To The Array List At Position 0
bowlersList.add(0, n);
//Refreshing The List
mAdapter.notifyDataSetChanged();
toggleEmptyBowlers();
}
}
//Updating Bowler In The Database And Updating The Item In The List By Its Position
private void updateBowler(String bowlerName, int position) {
Bowler n = bowlersList.get(position);
//Updating Bowler Text
n.setLeagueId(savedLeagueId);
n.setName(bowlerName);
//Updating The Bowler In The Database
db.updateBowler(n);
//Refreshing The List
bowlersList.set(position, n);
mAdapter.notifyItemChanged(position);
toggleEmptyBowlers();
}
//Deleting Bowler From SQLite Database And Removing The Bowler Item From The List By Its Position
private void deleteBowler(int position) {
//Deleting The Bowler From The Database
db.deleteBowler(bowlersList.get(position));
//Removing The Bowler From The List
bowlersList.remove(position);
mAdapter.notifyItemRemoved(position);
toggleEmptyBowlers();
}
//Opens Dialog With Edit/Delete Options
//Edit - 0
//Delete - 0
private void showActionsDialog(final int position) {
CharSequence colors[] = new CharSequence[]{"Edit", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose option");
builder.setItems(colors, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
showBowlerDialog(true, bowlersList.get(position), position);
} else {
deleteBowler(position);
}
}
});
builder.show();
}
//Show Alert Dialog With EditText Options to Enter/Edit A League
//When shouldUpdate = true, It Will Automatically Display Old Bowler Name And Change The Button Text To UPDATE
private void showBowlerDialog(final boolean shouldUpdate, final Bowler bowler, final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
View view = layoutInflaterAndroid.inflate(R.layout.dialog_bowler, null);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(BowlerActivity.this);
alertDialogBuilderUserInput.setView(view);
leagueId.setText(savedLeagueId);
final EditText inputBowlerName = view.findViewById(R.id.etBowlerNameInput);
TextView dialogTitle = view.findViewById(R.id.dialog_title);
dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_bowler_title) : getString(R.string.lbl_edit_bowler_title));
if (shouldUpdate && bowler != null) {
leagueId.setText(bowler.getLeagueId());
inputBowlerName.setText(bowler.getName());
}
alertDialogBuilderUserInput
.setCancelable(false)
.setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
})
.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
dialogBox.cancel();
}
});
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Show Toast Message When No Text Is Entered
if (TextUtils.isEmpty(inputBowlerName.getText().toString())) {
Toast.makeText(BowlerActivity.this, "Enter Bowler!", Toast.LENGTH_SHORT).show();
return;
} else {
alertDialog.dismiss();
}
//Check If User Is Updating Bowler
if (shouldUpdate && bowler != null) {
//Updating Bowler By Its Id
updateBowler(inputBowlerName.getText().toString(), position);
} else {
//Creating New Bowler
createBowler(leagueId.getText().toString(), inputBowlerName.getText().toString());
}
}
});
}
//Toggling List And Empty Bowler View
private void toggleEmptyBowlers() {
//You Can Check bowlerList.size() > 0
if (db.getBowlersCount() > 0) {
noBowlersView.setVisibility( View.GONE);
} else {
noBowlersView.setVisibility( View.VISIBLE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate( R.menu.menu_main, menu );
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected( item );
}
}
I have also include the DatabaseHelper portion that contains the Bowler methods.
public long insertBowler(String leagueId, String bowlerName) {
//Get Writable Database That We Want To Write Data Too
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//`id` and `timestamp` Will Be Inserted Automatically
values.put(Bowler.COLUMN_LEAGUE_ID, leagueId);
values.put(Bowler.COLUMN_NAME, bowlerName);
//Insert Row
long id = db.insert( Bowler.TABLE_NAME, null, values );
//Close Database Connection
db.close();
//Return Newly Inserted Row Id
return id;
}
public Bowler getBowler(String leagueId) {
//Get Readable Database If We Are Not Inserting Anything
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Bowler.TABLE_NAME,
new String[]{Bowler.COLUMN_ID, Bowler.COLUMN_LEAGUE_ID, Bowler.COLUMN_NAME, Bowler.COLUMN_TIMESTAMP},
Bowler.COLUMN_LEAGUE_ID + "=?",
new String[]{String.valueOf(leagueId)}, null, null, null, null);
if (cursor.moveToFirst()) {
//Prepare Bowler Object
Bowler bowler = new Bowler(
cursor.getInt(cursor.getColumnIndex(Bowler.COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_NAME)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));
//Close Database Connection
cursor.close();
return bowler;
} else {return null;}
}
public List<Bowler> getAllBowlers(String leagueId) {
List<Bowler> bowlers = new ArrayList<>();
//Select All Query
String selectQuery = "SELECT * FROM " + Bowler.TABLE_NAME + " WHERE " + Bowler.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " ORDER BY " +
Bowler.COLUMN_TIMESTAMP + " DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//Looping Through All Rows And Adding To The List
if (cursor.moveToFirst()) {
do {
Bowler bowler = new Bowler();
bowler.setId(cursor.getInt(cursor.getColumnIndex(Bowler.COLUMN_ID)));
bowler.setLeagueId(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)));
bowler.setName(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_NAME)));
bowler.setTimestamp(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));
bowlers.add(bowler);
} while (cursor.moveToNext());
}
cursor.close();
//Close Database Connection
db.close();
//Return Bowlers List
return bowlers;
}
public int getBowlersCount() {
String countQuery = "SELECT * FROM " + Bowler.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
//Return The Count
return count;
}
public int updateBowler(Bowler bowler) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Bowler.COLUMN_LEAGUE_ID, bowler.getLeagueId());
values.put(Bowler.COLUMN_NAME, bowler.getName());
//Updating Row
return db.update(Bowler.TABLE_NAME, values, Bowler.COLUMN_ID + " = ?",
new String[]{String.valueOf(bowler.getId())});
}
public void deleteBowler(Bowler bowler) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete( Bowler.TABLE_NAME, Bowler.COLUMN_ID + " = ?",
new String[]{String.valueOf( bowler.getId())});
db.close();
}
And just in case its required I have posted the BowlerAdapter code as well.
public class BowlerAdapter extends RecyclerView.Adapter<BowlerAdapter.MyViewHolder> {
private Context context;
private List<Bowler> bowlersList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView bowlerLeagueId;
public TextView name;
public TextView timestamp;
public MyViewHolder(View view) {
super(view);
bowlerLeagueId = view.findViewById( R.id.tvLeagueId);
name = view.findViewById(R.id.tvBowlerName );
timestamp = view.findViewById(R.id.timestamp);
}
}
public BowlerAdapter(Context context, List<Bowler> bowlersList) {
this.context = context;
this.bowlersList = bowlersList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.listview_bowler, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Bowler bowler = bowlersList.get(position);
holder.bowlerLeagueId.setText(bowler.getLeagueId());
holder.name.setText(bowler.getName());
//Formatting And Displaying Timestamp
holder.timestamp.setText(formatDate(bowler.getTimestamp()));
}
#Override
public int getItemCount() {
return bowlersList.size();
}
//Formatting TimeStamp to 'EEE MMM dd yyyy (HH:mm:ss)'
//Input : 2018-05-23 9:59:01
//Output : Wed May 23 2018 (9:59:01)
private String formatDate(String dateStr) {
try {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = fmt.parse(dateStr);
SimpleDateFormat fmtOut = new SimpleDateFormat("EEE MMM dd yyyy (HH:mm:ss)");
return fmtOut.format(date);
} catch (ParseException e) { }
return "";
}
I am sure its is something very obvious, but I have been looking at the code for a few hours and I just don't see the issue.
Any assistance would be appreciated.
I have amended my code as you indicated, but when I add a new bowler now the screen comes back blank until I leave the BowlerActivity and come back into it, at this point the list has been updated.
//Inserting New Bowler In The Database And Refreshing The List
private void createBowler(String leagueId, String bowlerName) {
//Inserting Bowler In The Database And Getting Newly Inserted Bowler Id
long id = db.insertBowler(leagueId, bowlerName);
//Get The Newly Inserted Bowler From The Database
Bowler n = db.getBowler(leagueId);
if (n != null) {
//Adding New Bowler To The Array List At Position 0
bowlersList.add(0, n);
//Refreshing The List
mAdapter.notifyDataSetChanged(bowlersList);
toggleEmptyBowlers();
}
}
BowlerAdapter notifyDataSetChanged method
private List<Bowler> bowlersList;
public void notifyDataSetChanged(List<Bowler> newbowlersList) {
bowlersList.clear();
bowlersList.addAll( newbowlersList );
super.notifyDataSetChanged();
}
Debugging Logs
this = {BowlerActivity#5027}
leagueId = "1"
bowlerName = "Robert"
id = 6
n = {Bowler#5032}
id = 1
league_id = "1"
name = "b1"
timestamp = "2018-06-07 20:03:19"
shadow$_klass_ = {Class#4839} "class ca.rvogl.tpbcui.database.models.Bowler"
shadow$_monitor_ = -2106571381
mAdapter = {BowlerAdapter#5033}
bowlersList = {ArrayList#5037} size = 0
mHasStableIds = false
mObservable = {RecyclerView$AdapterDataObservable#5088}
shadow$_klass_ = {Class#4930} "class ca.rvogl.tpbcui.views.BowlerAdapter"
shadow$_monitor_ = -2088753560
log.d log file snippet
06-08 13:00:53.807 29879-29879/ca.rvogl.tpbcui D/INSERTBOWLER: Number of bowlers in db = 4
06-08 13:00:53.814 29879-29884/ca.rvogl.tpbcui I/art: Do partial code cache collection, code=30KB, data=29KB
06-08 13:00:53.815 29879-29884/ca.rvogl.tpbcui I/art: After code cache collection, code=30KB, data=29KB
Increasing code cache capacity to 128KB
06-08 13:00:53.815 29879-29895/ca.rvogl.tpbcui D/EGL_emulation: eglMakeCurrent: 0x9e6fa300: ver 3 0 (tinfo 0xa068a610)
06-08 13:00:53.831 29879-29879/ca.rvogl.tpbcui W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
06-08 13:01:00.552 29879-29895/ca.rvogl.tpbcui D/EGL_emulation: eglMakeCurrent: 0x9e6fa300: ver 3 0 (tinfo 0xa068a610)
06-08 13:01:02.336 29879-29895/ca.rvogl.tpbcui D/EGL_emulation: eglMakeCurrent: 0x9e6fa300: ver 3 0 (tinfo 0xa068a610)
06-08 13:01:04.023 29879-29895/ca.rvogl.tpbcui D/EGL_emulation: eglMakeCurrent: 0x9e6fa300: ver 3 0 (tinfo 0xa068a610)
06-08 13:01:04.040 29879-29895/ca.rvogl.tpbcui D/EGL_emulation: eglMakeCurrent: 0x9e6fa300: ver 3 0 (tinfo 0xa068a610)
06-08 13:01:04.050 29879-29895/ca.rvogl.tpbcui D/EGL_emulation: eglMakeCurrent: 0x9e6fa300: ver 3 0 (tinfo 0xa068a610)
06-08 13:01:04.059 29879-29895/ca.rvogl.tpbcui D/EGL_emulation: eglMakeCurrent: 0x9e6fa300: ver 3 0 (tinfo 0xa068a610)
06-08 13:01:04.534 29879-29895/ca.rvogl.tpbcui D/EGL_emulation: eglMakeCurrent: 0x9e6fa300: ver 3 0 (tinfo 0xa068a610)
06-08 13:01:04.542 29879-29895/ca.rvogl.tpbcui D/EGL_emulation: eglMakeCurrent: 0x9e6fa300: ver 3 0 (tinfo 0xa068a610)
06-08 13:01:05.034 29879-29895/ca.rvogl.tpbcui D/EGL_emulation: eglMakeCurrent: 0x9e6fa300: ver 3 0 (tinfo 0xa068a610)
06-08 13:01:11.363 29879-29895/ca.rvogl.tpbcui D/EGL_emulation: eglMakeCurrent: 0x9e6fa300: ver 3 0 (tinfo 0xa068a610)
06-08 13:01:11.373 29879-29879/ca.rvogl.tpbcui D/INSERTBOWLER: Number of bowlers in db = 5
06-08 13:01:11.380 29879-29895/ca.rvogl.tpbcui D/EGL_emulation: eglMakeCurrent: 0x9e6fa300: ver 3 0 (tinfo 0xa068a610)
06-08 13:01:11.393 29879-29879/ca.rvogl.tpbcui W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
I believe that your issue is that you are not updating the actual source List within the adapter.
Reading Is Java “pass-by-reference” or “pass-by-value”?
may explain.
A resolution could be to be add a method to the BowlerAdapter e.g :-
public void notifyDatasetChanged(List<Bowler> newbowlerlist) {
bowlersList.clear();
bowlersList.addAll(newbowlerlist);
super.notifyDataSetChanged();
}
And to then use this new method, passing the amended bowlerlist, rather than the stock notifyDatasetChanged method.
e.g. instead of :-
if (n != null) {
//Adding New Bowler To The Array List At Position 0
bowlersList.add(0, n);
//Refreshing The List
mAdapter.notifyDataSetChanged();
toggleEmptyBowlers();
}
use :-
if (n != null) {
//Adding New Bowler To The Array List At Position 0
bowlersList.add(0, n);
//Refreshing The List
mAdapter.notifyDataSetChanged(bowlerList);
toggleEmptyBowlers();
}
Based upon you code using the above, the following results are obtained:-
Initial Display
2 Bowlers initially added when App starts.
Added button rather than code all the dialog handling (so clicking the button will add a new bowler, if the EditText isn't blank).
After Adding new Bowler
A new bowler was added by :-
Entering Howard in the EditText.
Clicking the Add Bowler button.
the List is refreshed displaying the added Bowler.
:-
Addition re comment :-
OK, insert is happening OK (you can remove the changes). Now make the
following changes to the getAllBowlers method (1 write the
selectQuery sql to the log, 2 write the number of rows retrieved to
the log and 3 write the size of the bowlers ArrayList to the
log). Run and report or fix.
public List<Bowler> getAllBowlers(String leagueId) {
List<Bowler> bowlers = new ArrayList<>();
//Select All Query
String selectQuery = "SELECT * FROM " + Bowler.TABLE_NAME + " WHERE " + Bowler.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " ORDER BY " +
Bowler.COLUMN_TIMESTAMP + " DESC";
Log.d("GETALLBOWLERS-SQL","SQL used = >>>>" +selectQuery + "<<<<");
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
Log.d("GETALLBOWLERS-CNT","Number of rows retrieved = " + String.valueOf(cursor.getCount()));
//Looping Through All Rows And Adding To The List
if (cursor.moveToFirst()) {
do {
Bowler bowler = new Bowler();
bowler.setId(cursor.getInt(cursor.getColumnIndex(Bowler.COLUMN_ID)));
bowler.setLeagueId(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)));
bowler.setName(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_NAME)));
bowler.setTimestamp(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));
bowlers.add(bowler);
} while (cursor.moveToNext());
}
cursor.close();
//Close Database Connection
db.close();
Log.d("GETALLBOWLERS-CNT","Number of elements in bowlerslist = " + String.valueOf(bowlers.size()));
//Return Bowlers List
return bowlers;
}
Working Example
I can't actually pinpoint your issue, although I do believe it's related to the original answer in that the Adapter works on/with a copy of of the bowler list, which is different to the bowler list passed to it. As such changing the bowlerlist in the activity does not change the bowlerlist in the adapter. As such issuing a onNotifyDatasetChanged after changing the bowlerlist is saying to the adapter that you've change the list in the adapter (i.e it's copy, which hasn't been changed).
As such the copy on the bowler list has to be changed and then the onNotifyDatasetChanged should be issued. My guess is that you didn't correctly implement the above.
As such I have virtually re-created your code and have a version that works :-
Instead of using an action bar a button is used to add a bowler.
Instead of this being invoked by anther activity and getting the LeagueID from the Intent Extra, the LeagueID is hard coded.
the ClickListener interface is included within the activity for my convenience.
The activity (I've called it BowlerActivity)
public class BowlerActivity extends AppCompatActivity {
private BowlerAdapter mAdapter;
private List<Bowler> bowlersList = new ArrayList<>();
private RecyclerView recyclerView;
private DatabaseHelper db;
private Button addbowler;
private EditText newbowler;
private TextView leagueId, noBowlersView;
private String savedLeagueId;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
addbowler = this.findViewById(R.id.addbowler); // For testing
leagueId = this.findViewById(R.id.tvLeagueId);
noBowlersView = this.findViewById(R.id.noBowlersView);
recyclerView = this.findViewById(R.id.recycler_view);
db = new DatabaseHelper(this);
savedLeagueId = "0"; //<<<< HARD CODED rather than get from IntentExtra
leagueId.setText(savedLeagueId);
bowlersList = db.getAllBowlers(leagueId.getText().toString());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mAdapter = new BowlerAdapter(this,bowlersList);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
//recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
recyclerView.setAdapter(mAdapter);
addbowler.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showBowlerDialog(false, null, -1);
}
});
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Toast.makeText(mContext,"You clicked me", Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(mContext,"You long clicked me", Toast.LENGTH_SHORT).show();
showActionsDialog(position);
}
}));
}
//Opens Dialog With Edit/Delete Options
//Edit - 0
//Delete - 0
private void showActionsDialog(final int position) {
CharSequence colors[] = new CharSequence[]{"Edit", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose option");
builder.setItems(colors, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
showBowlerDialog(true, bowlersList.get(position), position);
} else {
deleteBowler(position);
}
}
});
builder.show();
}
//Toggling List And Empty Bowler View
private void toggleEmptyBowlers() {
//You Can Check bowlerList.size() > 0
if (db.getBowlersCount() > 0) {
noBowlersView.setVisibility( View.GONE);
} else {
noBowlersView.setVisibility( View.VISIBLE);
}
}
//Inserting New Bowler In The Database And Refreshing The List
private void createBowler(String leagueId, String bowlerName) {
//Inserting Bowler In The Database And Getting Newly Inserted Bowler Id
long id = db.insertBowler(leagueId, bowlerName);
//Get The Newly Inserted Bowler From The Database
bowlersList = db.getAllBowlers(leagueId);
mAdapter.notifyDatasetChanged(bowlersList);
//mAdapter.notifyDataSetChanged();
}
//Updating Bowler In The Database And Updating The Item In The List By Its Position
private void updateBowler(String bowlerName, int position) {
Bowler n = bowlersList.get(position);
//Updating Bowler Text
n.setLeagueId(savedLeagueId);
n.setName(bowlerName);
//Updating The Bowler In The Database
db.updateBowler(n);
//Refreshing The List
bowlersList.set(position, n); //<<<<< does not change the bowlerlist in the adapter
//mAdapter.notifyItemChanged(position); // Saying that nothing has changed
mAdapter.notifyDatasetChanged(db.getAllBowlers(savedLeagueId)); //<<<<< rebuilds adapter bowler list
toggleEmptyBowlers();
}
//Deleting Bowler From SQLite Database And Removing The Bowler Item From The List By Its Position
private void deleteBowler(int position) {
//Deleting The Bowler From The Database
db.deleteBowler(bowlersList.get(position));
//Removing The Bowler From The List
bowlersList.remove(position);
//mAdapter.notifyItemRemoved(position); // Saying that nothing has changed
mAdapter.notifyDatasetChanged(db.getAllBowlers(savedLeagueId));
toggleEmptyBowlers();
}
public interface ClickListener{
void onClick(View view,int position);
void onLongClick(View view,int position);
}
//Show Alert Dialog With EditText Options to Enter/Edit A League
//When shouldUpdate = true, It Will Automatically Display Old Bowler Name And Change The Button Text To UPDATE
private void showBowlerDialog(final boolean shouldUpdate, final Bowler bowler, final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
View view = layoutInflaterAndroid.inflate(R.layout.dialog_bowler, null);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(BowlerActivity.this);
alertDialogBuilderUserInput.setView(view);
leagueId.setText(savedLeagueId);
final EditText inputBowlerName = view.findViewById(R.id.etBowlerNameInput);
TextView dialogTitle = view.findViewById(R.id.dialog_title);
dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_bowler_title) : getString(R.string.lbl_edit_bowler_title));
if (shouldUpdate && bowler != null) {
leagueId.setText(bowler.getLeagueId());
inputBowlerName.setText(bowler.getName());
}
alertDialogBuilderUserInput
.setCancelable(false)
.setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
})
.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
dialogBox.cancel();
}
});
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Show Toast Message When No Text Is Entered
if (TextUtils.isEmpty(inputBowlerName.getText().toString())) {
Toast.makeText(BowlerActivity.this, "Enter Bowler!", Toast.LENGTH_SHORT).show();
return;
} else {
alertDialog.dismiss();
}
//Check If User Is Updating Bowler
if (shouldUpdate && bowler != null) {
//Updating Bowler By Its Id
updateBowler(inputBowlerName.getText().toString(), position);
} else {
//Creating New Bowler
createBowler(leagueId.getText().toString(), inputBowlerName.getText().toString());
}
}
});
}
}
really the only change is using the onNotifyDatasetChanged(List<Bowler>) method rather than the stock onNotifyDatabsetChanged()
BowlerAdapter
public class BowlerAdapter extends RecyclerView.Adapter<BowlerAdapter.MyViewHolder> {
private Context context;
private List<Bowler> bowlersList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView bowlerLeagueId;
public TextView name;
public TextView timestamp;
public MyViewHolder(View view) {
super(view);
bowlerLeagueId = view.findViewById(R.id.tvLeagueId);
name = view.findViewById(R.id.tvBowlerName);
timestamp = view.findViewById(R.id.timestamp);
}
}
public BowlerAdapter(Context context, List<Bowler> bowlersList) {
this.context = context;
this.bowlersList = bowlersList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int fakeid = android.R.layout.simple_list_item_1;
int realid = R.layout.listview_boweler;
View itemView = LayoutInflater.from(parent.getContext())
.inflate(realid, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Bowler bowler = bowlersList.get(position);
holder.bowlerLeagueId.setText(bowler.getLeagueId());
holder.name.setText(bowler.getName());
//Formatting And Displaying Timestamp
holder.timestamp.setText(formatDate(bowler.getTimestamp()));
}
#Override
public int getItemCount() {
return bowlersList.size();
}
//<<<<<<<<<< Added >>>>>>>>>>
// This will get the actual bowler from the list
public Bowler getItemAtPosition(int position) {
return bowlersList.get(position);
}
//Formatting TimeStamp to 'EEE MMM dd yyyy (HH:mm:ss)'
//Input : 2018-05-23 9:59:01
//Output : Wed May 23 2018 (9:59:01)
private String formatDate(String dateStr) {
try {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = fmt.parse(dateStr);
SimpleDateFormat fmtOut = new SimpleDateFormat("EEE MMM dd yyyy (HH:mm:ss)");
return fmtOut.format(date);
} catch (ParseException e) {
}
return "";
}
public void notifyDatasetChanged(List<Bowler> newbowlerlist) {
bowlersList.clear();
bowlersList.addAll(newbowlerlist);
super.notifyDataSetChanged();
}
}
Note the notifyDatasetChanged(List<Bowler) method, this takes the changed bowler list and rebuilds the adapter's copy that it works with and then calls the adapter's notfiydatasetChanged method.
Added but not used is the getItemAtPosition method that can be used to return the bowler from the adapter at the given position (this could be used to circumvent altering the activity's copy of the bowlerlist).
DatabaseHelper
This just includes some changes that log's some information but is otherwise unchanged (although some missing code was added).
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "leagueapp.db";
public static final int DBVERSION = 1;
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(Bowler.CRTSQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long insertBowler(String leagueId, String bowlerName) {
//Get Writable Database That We Want To Write Data Too
SQLiteDatabase db = this.getWritableDatabase();
Log.d("INSERTBOWLER","Number of bowlers in db = " + String.valueOf(DatabaseUtils.queryNumEntries(db,Bowler.TABLE_NAME)));
ContentValues values = new ContentValues();
//`id` and `timestamp` Will Be Inserted Automatically
values.put(Bowler.COLUMN_LEAGUE_ID, leagueId);
values.put(Bowler.COLUMN_NAME, bowlerName);
//Insert Row
long id = db.insertOrThrow( Bowler.TABLE_NAME, null, values );
//Close Database Connection
db.close();
//Return Newly Inserted Row Id
return id;
}
public Bowler getBowler(String leagueId) {
//Get Readable Database If We Are Not Inserting Anything
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Bowler.TABLE_NAME,
new String[]{Bowler.COLUMN_ID, Bowler.COLUMN_LEAGUE_ID, Bowler.COLUMN_NAME, Bowler.COLUMN_TIMESTAMP},
Bowler.COLUMN_LEAGUE_ID + "=?",
new String[]{String.valueOf(leagueId)}, null, null, null, null);
if (cursor.moveToFirst()) {
//Prepare Bowler Object
Bowler bowler = new Bowler(
cursor.getLong(cursor.getColumnIndex(Bowler.COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_NAME)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));
//Close Database Connection
cursor.close();
return bowler;
} else {return null;}
}
public List<Bowler> getAllBowlers(String leagueId) {
List<Bowler> bowlers = new ArrayList<>();
//Select All Query
String selectQuery = "SELECT * FROM " + Bowler.TABLE_NAME + " WHERE " + Bowler.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " ORDER BY " +
Bowler.COLUMN_TIMESTAMP + " DESC";
Log.d("GETALLBOWLERS-SQL","SQL used = >>>>" +selectQuery + "<<<<");
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
Log.d("GETALLBOWLERS-CNT","Number of rows retrieved = " + String.valueOf(cursor.getCount()));
//Looping Through All Rows And Adding To The List
if (cursor.moveToFirst()) {
do {
Bowler bowler = new Bowler();
bowler.setId(cursor.getInt(cursor.getColumnIndex(Bowler.COLUMN_ID)));
bowler.setLeagueId(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)));
bowler.setName(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_NAME)));
bowler.setTimestamp(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));
bowlers.add(bowler);
} while (cursor.moveToNext());
}
cursor.close();
//Close Database Connection
db.close();
Log.d("GETALLBOWLERS-CNT","Number of elements in bowlerslist = " + String.valueOf(bowlers.size()));
//Return Bowlers List
return bowlers;
}
public int getBowlersCount() {
String countQuery = "SELECT * FROM " + Bowler.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
//Return The Count
return count;
}
public int updateBowler(Bowler bowler) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Bowler.COLUMN_LEAGUE_ID, bowler.getLeagueId());
values.put(Bowler.COLUMN_NAME, bowler.getName());
//Updating Row
return db.update(Bowler.TABLE_NAME, values, Bowler.COLUMN_ID + " = ?",
new String[]{String.valueOf(bowler.getId())});
}
public void deleteBowler(Bowler bowler) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete( Bowler.TABLE_NAME, Bowler.COLUMN_ID + " = ?",
new String[]{String.valueOf( bowler.getId())});
db.close();
}
public int deleteBowlerChecked(Bowler bowler) {
SQLiteDatabase db = this.getWritableDatabase();
Log.d("DELETEBOWLER","Attempting to DELETE bowler " + bowler.getName());
int rv = db.delete(Bowler.TABLE_NAME,Bowler.COLUMN_ID + "=?",
new String[]{String.valueOf(bowler.getId())});
if (rv < 1) {
Log.d("DELETEBOWLER", "Bowler with an id of " + String.valueOf(bowler.getId()) + " was not deleted, as it didn't exist.");
}
return rv;
}
}
RecyclerTouchListener
This wad added, it may or may not be the same as yours.
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private BowlerActivity.ClickListener clicklistener;
private GestureDetector gestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recycleView, final BowlerActivity.ClickListener clicklistener){
this.clicklistener=clicklistener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recycleView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null){
clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child=rv.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null && gestureDetector.onTouchEvent(e)){
clicklistener.onClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
Results/Testing
Initial Screen (empty db) :-
Add Bowler Button clicked :-
Bowler B1 entered and Save clicked :-
More Bowlers added :-
Bowler B5 updated :-
Bowlers B1 and B6 deleted :-

SQLite doesn't remove last object from db

I am doing an app that lets you write activities to do.
On the main activity, there's a ListView, which shows the activities according to the date especified in a DatePicker inside a DialogFragment.
I'm using SQLite to save the activities, and so far there's no problem saving them.
If you long press an item of the ListView, a context menu appears with a single option "Delete Activity", calling the method removeActivity, which deletes the activity from the static ArrayList System.activities, that stores every activity created, AND should delete the activity from the database, using the activity's attribute cod, which is unique for every instance of an activity.
public class Main extends FragmentActivity {
int mDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int mMonth = Calendar.getInstance().get(Calendar.MONTH); // August, month
// starts from 0
int mYear = Calendar.getInstance().get(Calendar.YEAR);
ArrayList<String> listNames = new ArrayList<String>();
List<ActivityToDo> acts = System.activities;
boolean listHasItems = false;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
removeActivitesBeforeCurrentDate();
ToDoSQLiteHelper actdb = new ToDoSQLiteHelper(this, "db", null, 1);
SQLiteDatabase db = actdb.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM Activities", null);
System.activities.clear();
if (c.moveToFirst()) {
do {
ActivityToDo act = new ActivityToDo(c.getString(1),
c.getString(2), c.getString(3));
act.setDate(Integer.parseInt(c.getString(4)),
Integer.parseInt(c.getString(5)),
Integer.parseInt(c.getString(6)));
System.activities.add(act);
} while (c.moveToNext());
}
db.close();
setContentView(R.layout.main);
final Button btnNewAct = (Button) findViewById(R.id.btnNewAct);
final TextView txtV = (TextView) findViewById(R.id.txtPickDate);
final ListView listview = (ListView) findViewById(R.id.listview);
listNames.add("Pick date to search activity.");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listNames);
listview.setAdapter(adapter);
registerForContextMenu(listview);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (listHasItems) {
ActivityToDo a = acts.get(position);
String[] datosAct = new String[6];
datosAct[0] = a.getName();
datosAct[1] = a.getDescr();
datosAct[2] = a.getPriority();
datosAct[3] = Integer.toString(a.getDay());
datosAct[4] = Integer.toString(a.getMonth());
datosAct[5] = Integer.toString(a.getYear());
Intent i = new Intent();
i.setClass(getApplicationContext(), ShowActivity.class);
i.putExtra("datos", datosAct);
startActivity(i);
}
}
});
final Handler mHandler = new Handler() {
// This handles the message send from DatePickerDialogFragment on
// setting date
#Override
public void handleMessage(Message m) {
Bundle b = m.getData();
mDay = b.getInt("set_day");
mMonth = b.getInt("set_month");
mYear = b.getInt("set_year");
String date = "";
if (mDay < 10) {
date += "0" + mDay + "/";
} else {
date += mDay + "/";
}
int mes = mMonth + 1;
if (mes < 10) {
date += "0" + mes + "/";
} else {
date += mes + "/";
}
date += mYear;
txtV.setText(date);
buildList(mDay, mMonth + 1, mYear);
}
};
OnClickListener listener = new OnClickListener() {
public void onClick(View v) {
Bundle b = new Bundle();
b.putInt("set_day", mDay);
b.putInt("set_month", mMonth);
b.putInt("set_year", mYear);
DatePickerDialogFragment datePicker = new DatePickerDialogFragment(
mHandler);
datePicker.setArguments(b);
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(datePicker, "date_picker");
// Opening the DatePicker fragment
ft.commit();
}
};
txtV.setOnClickListener(listener);
btnNewAct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(getApplicationContext(), NewActivity.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
protected void buildList(int d, int m, int y) {
acts = System.searchByDate(d, m, y);
listNames.clear();
if (acts != null && acts.size() != 0) {
for (int i = 0; i < acts.size(); i++) {
listNames.add(acts.get(i).getName());
}
listHasItems = true;
} else {
listHasItems = false;
listNames.add("No activities for that date.");
}
ListView listview = (ListView) findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listNames);
listview.setAdapter(adapter);
}
public void mostrarToast(String txt) {
Toast toast = Toast.makeText(getApplicationContext(), txt,
Toast.LENGTH_SHORT);
toast.show();
}
private void removeActivitesBeforeCurrentDate() {
ToDoSQLiteHelper actdb = new ToDoSQLiteHelper(getApplicationContext(),
"db", null, 1);
SQLiteDatabase db = actdb.getWritableDatabase();
ActivityToDo aux;
Cursor c = db.rawQuery("SELECT * FROM Activities", null);
if (System.activities.size() != 0 && c.moveToFirst()) {
for (int i = 0; i < System.activities.size(); i++) {
aux = System.activities.get(i);
if (aux.getYear() < Calendar.getInstance().get(Calendar.YEAR)
&& aux.getMonth() - 1 < Calendar.getInstance().get(
Calendar.MONTH)
&& aux.getDay() < Calendar.getInstance().get(
Calendar.DAY_OF_MONTH)) {
System.activities.remove(i);
int cod = aux.getCod();
db.execSQL("DELETE FROM Activities WHERE cod=" + cod);
}
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (listHasItems) {
MenuInflater inflater = getMenuInflater();
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
position = info.position;
inflater.inflate(R.menu.menulistitem, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
removeActivity(position);
buildList(mDay, mMonth + 1, mYear);
return true;
}
private void removeActivity(int pos) {
ToDoSQLiteHelper actdb = new ToDoSQLiteHelper(getApplicationContext(),
"db", null, 1);
SQLiteDatabase db = actdb.getWritableDatabase();
ActivityToDo aux;
Cursor c = db.rawQuery("SELECT * FROM Activities", null);
if (System.activities.size() != 0 && c.moveToFirst()) {
aux = System.activities.get(pos);
System.activities.remove(pos);
int cod = aux.getCod();
db.execSQL("DELETE FROM Activities WHERE cod=" + cod);
}
c.close();
}
#Override
protected void onPause() {
super.onPause();
this.finish();
}
}
But the db.execSQL("DELETE FROM Activities WHERE cod=" + cod); doesn't seem to work for the last activity that remains in the database. Example: I pick a date, there's two activities for the day, I delete both of them, the ListView shows the text "No activity for that date", which is what should happen, but when I start the app again, the activity that was supposingly deleted at last, appears there. Same if there's only one activity for that date, that's why I say that it doesn't seem to delete an activity if it's the last thing in the database.
Any idea why? Thanks in advance.
My SQLite class:
public class ToDoSQLiteHelper extends SQLiteOpenHelper {
// crear tabla de usuario
// agregar DATE
String sqlCreate = "CREATE TABLE Activities (cod INTEGER, name TEXT, descr TEXT, priority TEXT, day TEXT, month TEXT, year TEXT)";
public ToDoSQLiteHelper(Context contexto, String nombre,
CursorFactory factory, int version) {
super(contexto, nombre, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(sqlCreate);
}
#Override
public void onUpgrade(SQLiteDatabase db, int versionAnterior,
int versionNueva) {
db.execSQL("DROP TABLE IF EXISTS Activities");
db.execSQL(sqlCreate);
}
}

Categories