null value on variable passed from inside a onclick response - java

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);
}
}

Related

Bundle/getArguments() gives NullPtrException

I want to pass an ArrayList to my fragment from my activity that is accessed through the bottom navigation bar, the bundle returns null when I call getInt() or getParcelableArrayList()
EDIT: pasted whole files, in hope that will help... + put the bundle in on create(didn't help)
Code:
main activity(where it's sent)
public class MainActivity extends AppCompatActivity {
private BottomNavigationView bottomNavigationView;
private AdView mAdView;
private boolean isAdsRemoved;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private List<AppListModel> list = new ArrayList<>();
private int totalUsage = 0;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!checkForPermission(this)) {
startActivity(new Intent(this, CheckForPermissionActivity.class));
finish();
}
long startTime = System.currentTimeMillis() - 86400000;
long endTime = System.currentTimeMillis();
UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService("usagestats");
List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);
for (UsageStats us : queryUsageStats) {
Drawable icon;
int totalTimeMin = (int) us.getTotalTimeInForeground() / 60000;
boolean alreadyThere = false;
PackageManager pm = getPackageManager();
ApplicationInfo ai;
if (us.getPackageName().equals("com.android.systemui")) {
continue;
}
try {
ai = pm.getApplicationInfo(us.getPackageName(), 0);
icon = getPackageManager().getApplicationIcon(us.getPackageName());
} catch (PackageManager.NameNotFoundException e) {
ai = null;
icon = null;
Log.d(TAG, "Package name not found");
e.printStackTrace();
}
String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
if (applicationName.length() > 15) {
applicationName = applicationName.substring(0, Math.min(applicationName.length(), 13)) + "...";
}
//if packages that have the same names, but are registered multiple times, they are merged
if (list.size() > 0) {
for (AppListModel item : list) {
if (item.getAppName().equals(applicationName)) {
item.setTotalTime(totalTimeMin + item.getTotalTime());
totalUsage += totalTimeMin;
alreadyThere = true;
}
}
}
if (totalTimeMin > 0 && !alreadyThere) {
if (!applicationName.equals("(unknown)")) {
list.add(new AppListModel(applicationName, icon, totalTimeMin));
}
Log.d(TAG, us.getPackageName() + " = " + us.getTotalTimeInForeground());
totalUsage += totalTimeMin;
}
}
preferences = getSharedPreferences("label", 0);
if (preferences.getBoolean("ad_removed", false)) {
isAdsRemoved = true;
}
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
if (preferences.getBoolean("ad_removed", false)) {
mAdView.setVisibility(View.GONE);
}
if (!preferences.getBoolean("ad_removed", false) && !isAdsRemoved) {
Intent intent = getIntent();
isAdsRemoved = intent.getBooleanExtra("ad_removal", false);
}
editor = preferences.edit();
editor.putBoolean("ad_removed", isAdsRemoved).commit();
bottomNavigationView = findViewById(R.id.bottomNavigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
bottomNavigationView.setSelectedItemId(R.id.itemDashboard);
Fragment dashboard = new FragmentDashboard();
ArrayList<AppListModel> arrayList = new ArrayList<>(list.size());
arrayList.addAll(list);
Bundle bundle = new Bundle();
bundle.putInt("totalUsage", totalUsage);
bundle.putParcelableArrayList("arrayList", arrayList);
dashboard.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, dashboard).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.itemStats:
selectedFragment = new FragmentStats();
break;
case R.id.itemDashboard:
selectedFragment = new FragmentDashboard();
break;
case R.id.itemStore:
selectedFragment = new FragmentStore();
break;
case R.id.itemSettings:
selectedFragment = new FragmentSettings();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, selectedFragment).commit();
return true;
}
};
private boolean checkForPermission(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
return (mode == AppOpsManager.MODE_ALLOWED);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
}
FragmentDashboard
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//View itself
view = inflater.inflate(R.layout.fragment_dashboard, container, false);
//'TIME WASTED' counter
count = view.findViewById(R.id.mainFragmentText);
//RecyclerView
recyclerView = view.findViewById(R.id.recyclerView);
//Buttons
showAllBtn = view.findViewById(R.id.showAllButton);
hideBtn = view.findViewById(R.id.hideAllButton);
timeNotifBtn = view.findViewById(R.id.timeButton);
stopLimiterButton = view.findViewById(R.id.disableLimit);
list = getArguments().getParcelableArrayList("arrayList");
totalUsage = getArguments().getInt("totalUsage", 0);
int totalUsageHrs = (int) totalUsage / 60;
int totalUsageMin = (int) totalUsage - totalUsageHrs * 60;
if (totalUsageHrs == 0) {
count.setText(totalUsageMin + " minutes");
} else {
count.setText(totalUsageHrs + " hours, " + totalUsageMin + " minutes");
}
//sorts list in descending order
Collections.sort(list, new Comparator<AppListModel>() {
#Override
public int compare(AppListModel appListModel, AppListModel t1) {
return Integer.valueOf(t1.getTotalTime()).compareTo(Integer.valueOf(appListModel.getTotalTime()));
}
});
mostUsedApps = list.subList(0, Math.min(list.size(), 3));
adapter = new RVAdapterDashboard(getActivity());
adapter.setList(mostUsedApps);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
showAllBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter = new RVAdapterDashboard(getActivity());
adapter.setList(list);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
showAllBtn.setVisibility(View.INVISIBLE);
hideBtn.setVisibility(View.VISIBLE);
}
});
hideBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hideBtn.setVisibility(View.GONE);
adapter = new RVAdapterDashboard(getActivity());
adapter.setList(mostUsedApps);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
showAllBtn.setVisibility(View.VISIBLE);
hideBtn.setVisibility(View.INVISIBLE);
}
});
timeNotifBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (totalUsage > 720) {
Toast.makeText(getActivity(), "Take a break, you have spent too much on your phone", Toast.LENGTH_SHORT).show();
} else {
DialogDashboard dialogDashboard = new DialogDashboard();
dialogDashboard.show(getChildFragmentManager(), "notif_dialog");
}
}
});
stopLimiterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isJobServiceOn(getActivity())) {
JobScheduler scheduler = (JobScheduler) getActivity().getSystemService(Context.JOB_SCHEDULER_SERVICE);
scheduler.cancel(JOB_ID);
} else {
Toast.makeText(getActivity(), "No limit set", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList android.os.Bundle.getParcelableArrayList(java.lang.String)' on a null object reference
at com.example.dashboard.FragmentDashboard.onCreateView(FragmentDashboard.java:78)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1395)
at android.app.Activity.performStart(Activity.java:7348)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3145)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7078)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
EDIT 2, I fixed the problem, I just put the bundle in both onCreate and onMenuItemSelected
case R.id.itemStats:
selectedFragment = new FragmentDashboard();
ArrayList<AppListModel> arrayList = new ArrayList<>(list.size());
arrayList.addAll(list);
Bundle bundle = new Bundle();
bundle.putInt("totalUsage", totalUsage);
bundle.putParcelableArrayList("arrayList", arrayList);
selectedFragment.setArguments(bundle);
break;
case R.id.itemDashboard:
selectedFragment = new FragmentDashboard();
break;
In this part of your code you instantiate FragmentDashboard in two case statement which in second one you did not pass any bundle as arguments and because this you get error when you call getArguments().get... in it.
You only set the arguments on your FragmentStats instance. Other fragments such as the FragmentDashboard seen in the stacktrace don't have arguments set, and getArguments() returns null.
If you want the same arguments to be applied to all fragments, move the Bundle setup and setArguments() after the switch-case. (And maybe add a default case too so selectedFragment won't ever be null.)

ListView Not Displaying in New Activity

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

How to get all items in arraylist and display it in a listview

public class ChatBubbleActivity extends AppCompatActivity {
private static final String TAG = "ChatActivity";
Toolbar toolbar;
TextView tv_name;
List<ListData> dataList;
int user_id;
int msg_type = 1;
DatabaseHelper databaseHelper;
private ListView listView;
private EditText chatText;
private ImageButton buttonSend;
private String name, message, time;
private ChatArrayAdapter chatArrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
name = getIntent().getStringExtra("name");
user_id = getIntent().getIntExtra("user_id", 0);
databaseHelper = new DatabaseHelper(this);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back);
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
toolbar.setSubtitleTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
receiveMessage();
tv_name = findViewById(R.id.tv_name);
buttonSend = findViewById(R.id.buttonSend);
listView = findViewById(R.id.listView1);
chatText = findViewById(R.id.chatText);
listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
listView.setAdapter(chatArrayAdapter);
chatArrayAdapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
listView.setSelection(chatArrayAdapter.getCount() - 1);
}
});
tv_name.setText(name);
}
private void receiveMessage() {
dataList = new ArrayList<>();
dataList = databaseHelper.getSingleUserMsg(user_id);
for (int i = 0; i < dataList.size(); i++) {
ListData listData=dataList.get(i);
message = listData.getMessage();
time = listData.getCreated_at();
msg_type = listData.getMsg_type();
Log.d("Message",message);
Date dateTime = null;
try {
dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a").parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateTime);
DateFormat timeFormatter = new SimpleDateFormat("h:mm a");
int layout_resource;
if (dataList.get(i).getMsg_type() == 0) {
layout_resource = R.layout.item_chat_left;
} else {
layout_resource = R.layout.item_chat_right;
}
chatArrayAdapter = new ChatArrayAdapter(getApplicationContext(), layout_resource, dataList, msg_type);
chatArrayAdapter.add(new ChatMessage(message, timeFormatter.format(dateTime)));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.conversation_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my Chat screen activity.I retrieve the values from the sqlite database and store it in a arraylist. When i try to get the data from the arraylist and show in the listview it also shows last item in the arraylist. How to get all the items in arraylist and load it in the listview. How to do this? Please help to do this
public List<ListData> getSingleUserMsg(int user_id) {
List<ListData> listData = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select message,created_at,msg_type from " + TABLE_MSG + " WHERE " + USER_ID + " = " + user_id + " ORDER BY " + CREATED_AT + ";", null);
ListData listData1;
while (cursor.moveToNext()) {
listData1 = new ListData();
String message = cursor.getString(cursor.getColumnIndexOrThrow("message"));
String created_at = cursor.getString(cursor.getColumnIndexOrThrow("created_at"));
String msg_type = cursor.getString(cursor.getColumnIndexOrThrow("msg_type"));
listData1.setMessage(message);
listData1.setMsg_type(Integer.parseInt(msg_type));
listData1.setCreated_at(created_at);
listData.add(listData1);
}
return listData;
}
The above code is the method of database helper.
Write this lines outside your for loop.
chatArrayAdapter = new ChatArrayAdapter(getApplicationContext(), layout_resource, dataList, msg_type);
chatArrayAdapter.add(new ChatMessage(message, timeFormatter.format(dateTime)));
Add adapter code in outside of the loop and refresh the list.Because your calling receiveMessage() after that only your setting adapter that is the issue
1.Main Activity call method like this after listView initialization call receiveMessage()
tv_name = findViewById(R.id.tv_name);
buttonSend = findViewById(R.id.buttonSend);
listView = findViewById(R.id.listView1);
chatText = findViewById(R.id.chatText);
listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
receiveMessage();
private void receiveMessage() {
dataList = new ArrayList<>();
dataList = databaseHelper.getSingleUserMsg(user_id);
for (int i = 0; i < dataList.size(); i++) {
ListData listData=dataList.get(i);
message = listData.getMessage();
time = listData.getCreated_at();
msg_type = listData.getMsg_type();
Log.d("Message",message);
Date dateTime = null;
try {
dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a").parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateTime);
DateFormat timeFormatter = new SimpleDateFormat("h:mm a");
int layout_resource;
if (dataList.get(i).getMsg_type() == 0) {
layout_resource = R.layout.item_chat_left;
} else {
layout_resource = R.layout.item_chat_right;
}
}
chatArrayAdapter = new ChatArrayAdapter(getApplicationContext(), layout_resource, dataList, msg_type);
chatArrayAdapter.add(new ChatMessage(message, timeFormatter.format(dateTime)));
listView.setAdapter(chatArrayAdapter);
}

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);
}
}

TimePicker Saves Zero Value in SQLite Database

I have a TimePicker which I'd like to use to determine a length of time a user can stay connected. Lets say the time now is 10:00 if the user selects 11:00 - I'd like the source code below to determine that there are 60 minutes between the current time - and the time selected and set that to a string/long (minutes) which I then have displayed as a textview.
I've coded everything as I thought it should be - however the textview never seems to update with minutes value. Everytime I attempt to view the data - I get a value of 0 not matter what the timepicker is set to.
Anyone have any suggestions? I'm stumped at the moment and I'm not sure what else to try.
ADDEDITDEVICE.JAVA (where the timepicker and minutes determination takes place)
public class AddEditDevice extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
private TextView ssidTextView;
Date date = new Date();
TimePicker tp;
// #Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String ssidString = info.getSSID();
if (ssidString.startsWith("\"") && ssidString.endsWith("\"")){
ssidString = ssidString.substring(1, ssidString.length()-1);
//TextView ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView.setText(ssidString);
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
String time = extras.getString("time");
String[] parts = time.split(":");
timeEt.setCurrentHour(Integer.valueOf(parts[0]));
timeEt.setCurrentMinute(Integer.valueOf(parts[1]));
timeEt.setIs24HourView(false);
date.setMinutes(tp.getCurrentMinute());
date.setHours(tp.getCurrentHour());
Long.toString(minutes);
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(AddEditDevice.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});}
}
long minutes = ((new Date()).getTime() - date.getTime()) / (1000 * 60);
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
// Log.i("Test for Null", ""+dbConnector+" "+nameEt+" "+capEt+" "+timeEt+" "+codeEt+" "+ssidTextView);
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
Long.toString(minutes),
ssidTextView.getText().toString());
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
Long.toString(minutes),
ssidTextView.getText().toString());
}
}
}
VIEW COUNTRY.JAVA (where the minutes data set by the timepicker should be visible)
public class ViewCountry extends NfcBeamWriterActivity {
private static final String TAG = ViewCountry.class.getName();
protected Message message;
NfcAdapter mNfcAdapter;
private static final int MESSAGE_SENT = 1;
private long rowID;
private TextView nameTv;
private TextView capTv;
private TextView codeTv;
private TextView timeTv;
private TextView ssidTv;
private TextView combined;
private TextView minutes;
//String timetest = "300";
// String a="\"";
// String b="\"";
// String message1 = a + ssidTv.getText().toString() +"," +
// capTv.getText().toString()+b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_country);
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("name", true);
editor.putBoolean("cap", true);
editor.putBoolean("code", true);
editor.putBoolean("time", true);
editor.putBoolean("ssid",true);
editor.putBoolean("minutes",true);
editor.putBoolean("timetest",true);
editor.commit();
setDetecting(true);
startPushing();
setUpViews();
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(CountryList.ROW_ID);
}
private void setUpViews() {
nameTv = (TextView) findViewById(R.id.nameText);
capTv = (TextView) findViewById(R.id.capText);
timeTv = (TextView) findViewById(R.id.timeEdit);
codeTv = (TextView) findViewById(R.id.codeText);
ssidTv = (TextView) findViewById(R.id.wifiSSID);
minutes = (TextView) findViewById(R.id.Minutes);
}
#Override
protected void onResume() {
super.onResume();
new LoadContacts().execute(rowID);
}
private class LoadContacts extends AsyncTask<Long, Object, Cursor> {
DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this);
#Override
protected Cursor doInBackground(Long... params) {
dbConnector.open();
return dbConnector.getOneContact(params[0]);
}
#Override
protected void onPostExecute(Cursor result) {
super.onPostExecute(result);
result.moveToFirst();
int nameIndex = result.getColumnIndex("name");
int capIndex = result.getColumnIndex("cap");
int codeIndex = result.getColumnIndex("code");
int timeIndex = result.getColumnIndex("time");
int ssidIndex = result.getColumnIndex("ssid");
nameTv.setText(result.getString(nameIndex));
capTv.setText(result.getString(capIndex));
timeTv.setText(result.getString(timeIndex));
codeTv.setText(result.getString(codeIndex));
ssidTv.setText(result.getString(ssidIndex));
result.close();
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.editItem:
Intent addEditContact = new Intent(this, AddEditDevice.class);
// addEditContact.putExtra(CountryList.ROW_ID, rowID);
// addEditContact.putExtra("name", nameTv.getText());
// addEditContact.putExtra("cap", capTv.getText());
// addEditContact.putExtra("code", codeTv.getText());
startActivity(addEditContact);
return true;
case R.id.user1SettingsSave:
Intent Tap = new Intent(this, Tap.class);
startActivity(Tap);
return true;
case R.id.deleteItem:
deleteContact();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteContact() {
AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) {
final DatabaseConnector dbConnector = new DatabaseConnector(
ViewCountry.this);
AsyncTask<Long, Object, Object> deleteTask = new AsyncTask<Long, Object, Object>() {
#Override
protected Object doInBackground(Long... params) {
dbConnector.deleteContact(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result) {
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
});
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
}
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":" + timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
minutes,
Long.toString(minutes),
ssidTextView.getText().toString());
You have that code to add a contact, BUT in your database conector you have:
public void insertContact(String name,
String cap,
String code,
String time,
long minutes,
String ssid,
String string){
I think that don't match, so this is why don't insert correctly.
BTW i can't comment at the moment because i need 50 reputation.
Regards
USE CREATE TABLE IF NOT EXISTS T/N then your problem wil be solved.
otherwise it will override the current table at the same time all the data will be lost.

Categories