Update/Edit Sqlite Database using SimpleCursorAdapter via onClick ImageView - java

Illustration
Please see image first..
How can i get value "Test 1" and after that i want update column (favorite) in sqlite database to "Yes"?
I was searching to find answer for my case but there is no match with my problem, or maybe I am the one who doesn't understand.. :D
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_channel_list);
channelList = this.findViewById(R.id.channelList);
mDB = openDB();
if (mDB != null) {
mCsr = mDB.query(CHANNELTABLE,
new String[]{KEY_NO + " AS _id",
KEY_NAME, KEY_CATEGORY, KEY_LOGO, KEY_SERVER1, KEY_SERVER2, KEY_SERVER3, KEY_SERVER4, KEY_SERVER5, KEY_LIKE
},
null,null,null,null,null);
mSCA = new SimpleCursorAdapter(this,R.layout.custom_listview,mCsr,
new String[]{KEY_NAME, KEY_CATEGORY, KEY_LOGO, KEY_LIKE},
new int[]{R.id.channel_name, R.id.category, R.id.logo, R.id.like},0);
mSCA.setViewBinder(new SimpleCursorAdapter.ViewBinder(){
public boolean setViewValue(final View view, Cursor cursor, int columnIndex){
if(view.getId() == R.id.logo){
channelName = cursor.getString(3);
int resID = getResources().getIdentifier(channelName, "drawable", getPackageName());
//Toast.makeText(Channel_List_Act.this, cursor.getString(9), Toast.LENGTH_LONG).show();
((ImageView)view.findViewById(R.id.logo)).setImageDrawable(getResources().getDrawable(resID, getApplicationContext().getTheme()));
return true;
}
if(view.getId() == R.id.like){
liked = cursor.getString(9);
final int resID = getResources().getIdentifier(liked, "drawable", getPackageName());
((ImageView)view.findViewById(R.id.like)).setImageDrawable(getResources().getDrawable(resID, getApplicationContext().getTheme()));
((ImageView)view.findViewById(R.id.like)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
I AM STUCK IN HERE, OR MAYBE NOT HERE?
}
});
return true;
}
return false;
}
});
channelList.setAdapter(mSCA);
} else {
Toast.makeText(this,"Unable to open Database.",Toast.LENGTH_LONG).show();
}
}

this is weird to answer my own question.. :D
//This is for getting Textview and Imageview from custom_listview.xml
RelativeLayout vwParentRow = (RelativeLayout)v.getParent();
TextView child = (TextView)vwParentRow.getChildAt(1);
ImageView btnChild = (ImageView)vwParentRow.getChildAt(3);
//This is for changing image to favorited or no
assert (R.id.like == btnChild.getId());
Integer integer = (Integer) btnChild.getTag();
integer = integer == null ? 0 : integer;
switch(integer) {
case R.drawable.yes:
btnChild.setImageResource(R.drawable.no);
btnChild.setTag(R.drawable.no);
//This is to update database
mDB.execSQL("UPDATE Channel_Info SET Favourite='no' WHERE name='" + child.getText() + "'");
break;
case R.drawable.no:
default:
btnChild.setImageResource(R.drawable.yes);
btnChild.setTag(R.drawable.yes);
mDB.execSQL("UPDATE Channel_Info SET Favourite='yes' WHERE name='" + child.getText() + "'");
break;
}
Get the ID of a drawable in ImageView
I am forgot.
Forgot

Related

getting value from different activities with getParcelableExtra()

I have two activities that are called DrinksActivity and FoodsActivity. Both have their own RecyclerViews to display items.
They work well, but I have to pass their values to another activity called.. sample_activity.
This is how sample_activity looks like.
public class sample_layout extends AppCompatActivity {
private DrawerLayout dl;
private ActionBarDrawerToggle t;
private NavigationView nv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_layout);
SetTexts();
Navigation();
TextView textView = findViewById(R.id.txtFoodName);
Intent intent = getIntent();
DrinksModel drinksM = intent.getParcelableExtra("drinks");
FoodModel foodM = intent.getParcelableExtra("foods");
//how can i set the textView from their own getParcelableExtra values
String FoodName = foodM.getFoodName();
textView.setText(FoodName);
//how can i set the textView from their own getParcelableExtra values
String DrinkName = drinksM.getDrinkName();
textView.setText(DrinkName);
}
public String getName(String email) {
String stringList = null;
DatabaseHelperAccounts db = new DatabaseHelperAccounts(this);
SQLiteDatabase dbb = db.getWritableDatabase();
String selectQuery = "SELECT FullName FROM " + db.DATABASE_TABLE + " WHERE email = '" + email + "'";
Cursor c = dbb.rawQuery(selectQuery, null);
if (c != null) {
c.moveToFirst();
while (c.isAfterLast() == false) {
String name2 = (c.getString(c.getColumnIndex("FullName")));
stringList = name2;
c.moveToNext();
}
}
return stringList;
}
public void SetTexts() {
String StringEmail = LoginFragment.EmailString;
NavigationView nav_view = (NavigationView) findViewById(R.id.nv);//this is navigation view from my main xml where i call another xml file
View header = nav_view.getHeaderView(0);//set View header to nav_view first element (i guess)
TextView UserFullNameNav = (TextView) header.findViewById(R.id.UserFullNameNav);//now assign textview imeNaloga to header.id since we made View header.
TextView UserEmailNav = (TextView) header.findViewById(R.id.UserEmailNav);
getName(StringEmail);
UserEmailNav.setText(StringEmail);// And now just set text to that textview
UserFullNameNav.setText(getName(StringEmail));
}
public void Navigation() {
dl = findViewById(R.id.sampleLayout);
t = new ActionBarDrawerToggle(this, dl, R.string.open, R.string.close);
dl.addDrawerListener(t);
t.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nv = findViewById(R.id.nv);
nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.itemDrinks:
Intent DrinksIntent = new Intent(getApplicationContext(), DrinksActivity.class);
startActivity(DrinksIntent);
break;
case R.id.itemFoods:
Intent FoodsIntent = new Intent(getApplicationContext(), FoodsActivity.class);
startActivity(FoodsIntent);
break;
case R.id.itmLogout:
Intent LogOut = new Intent(getApplicationContext(), MainActivity.class);
startActivity(LogOut);
finish();
default:
return true;
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull 'MenuItem' item)
{
if ( t.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
}
How can I get the value of the item when it is chosen from the recyclerview of that specific activity?
Try to use this
if (getIntent()!=null ){
if (getIntent.hasExtra("drinks")){
DrinksModel drinksM = intent.getParcelableExtra("drinks");
String DrinkName = drinksM.getDrinkName();
textView.setText(DrinkName);
}else if(getIntent.hasExtra("foods")){
FoodModel foodM = intent.getParcelableExtra("foods");
String FoodName = foodM.getFoodName();
textView.setText(FoodName);
}
}
As I can see you're using database to store data, right? If so, the best (and the most correct) way is to pass some identifier between activity (like "id") and then get value by that id from database where you need. But, if you really want to pass the whole object then you need to use serializable or parcelable (parcelable is better choice since it's from Android SDK). Then in the activity where you're getting the value just parse it.
EDIT:
To get parcelable value call:
Food food = getIntent().getExtras().getParcelable("food");
Then just call:
textView.setText(food.getYourField);

Getting the Bowler Count to Display in League RecyclerView

I have a list of Leagues that that I want to display the number of bowlers for in each entry. For Example:
I want to display a count of the number of bowlers in each list under each League name in the list. For Example:
This is meant to be a quick view about each League.
I tried to accomplish this with the following code:
DatabaseHelper
//Getting Number of Bowlers in League
public String leagueBowlerCount(String leagueId)
{
SQLiteDatabase db = this.getReadableDatabase();
String countQuery = "SELECT * FROM " + Bowler.TABLE_NAME + " WHERE " + Bowler.COLUMN_LEAGUE_ID + " = '" + leagueId + "'";
Cursor cursor = db.rawQuery(countQuery, null);
int count = 0;
if(null != cursor)
if(cursor.getCount() > 0){
cursor.moveToFirst();
count = cursor.getInt(0);
}
cursor.close();
db.close();
return String.valueOf(count);
}
League Adapter
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView id;
public TextView name;
public TextView baseScore;
public TextView basePercentage;
public TextView bowlerCount;
TextView timestamp;
public TextView buttonViewOption;
MyViewHolder(View view) {
super(view);
if (!(itemView instanceof AdView)) {
id = view.findViewById( R.id.tvLeagueId);
name = view.findViewById(R.id.tvLeagueName );
baseScore = view.findViewById( R.id.tvBaseScore);
basePercentage = view.findViewById(R.id.tvBaseScorePercentage);
bowlerCount = view.findViewById(R.id.tvNumberOfBowlers);
timestamp = view.findViewById(R.id.timestamp);
buttonViewOption = view.findViewById(R.id.buttonViewOptions);
}
}
}
public LeagueAdapter(Context context, List<League> leaguesList) {
this.context = context;
this.leaguesList = leaguesList;
mainActivity = (Activity) context;
inflater = LayoutInflater.from(context);
}
public LeagueAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
AdView adview;
MyViewHolder holder;
if (viewType == AD_TYPE) {
adview = new AdView(mainActivity);
adview.setAdSize( AdSize.BANNER);
// this is the good adview
adview.setAdUnitId(mainActivity.getString(R.string.admob_ad_id));
float density = mainActivity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, height);
adview.setLayoutParams(params);
// dont use below if testing on a device
// follow https://developers.google.com/admob/android/quick-start?hl=en to setup testing device
AdRequest request = new AdRequest.Builder().build();
adview.loadAd(request);
holder = new MyViewHolder(adview);
}else{
View view = inflater.inflate(R.layout.listview_league, parent, false);
holder = new MyViewHolder(view);
}
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
if(position % 10 != 5) {
League league = leaguesList.get(position);
int id = league.getId();
String leagueId = String.valueOf(id);
holder.id.setText(leagueId);
holder.name.setText(league.getName());
holder.baseScore.setText(league.getBasisScore());
holder.basePercentage.setText(league.getBaseScorePercentage());
holder.bowlerCount.setText(db.leagueBowlerCount(leagueId));
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();
((MainActivity) context).openDialog(true, leaguesList.get(position), position);
break;
case R.id.delete:
((MainActivity) context).deleteLeague(position);
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
}
}
I have been messing around with this for a number of days, I cannot figure out why this will not work. Any assistance would be greatly appreciated. I am thinking that there is probably a much easier way of accomplishing this that I am not aware of.
In the logcat I am seeing the following message:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String ca.vogl.r.tenpinbowlingcompanion.database.DatabaseHelper.leagueBowlerCount(java.lang.String)' on a null object reference.
As was pointed out below, the error seems to be happening in leagueBowlerCount(), which is listed above.
After making making the following addition to the onBindViewHolder : db = new DatabaseHelper (mainActivity). I am seeing values where I should be but they are not correct. See images below.
Test League 1 (there are three bowlers, one is hidden by the test ad)
Test League 2 (there is only 1 bowler)
Test League 3 (there are three bowlers, one is hidden by the test ad)
So basically you should be seeing a 3 for Test League 1, a 1 for Test League 2 and a 3 for Test League 3
So it now seems that the problem is with the leagueBowlercount function that I wrote. It is not getting the counts that are associated only to the individual league Id
I believe that your issue is that you are returning the id of the first selected bowler rather than the row count.
That is you, after checking the number of rows is greater than 0, move to the first row and then use count = cursor.getInt(0); which will be the value stored in the first column of the first row that has been extracted.
try using :-
public String leagueBowlerCount(String leagueId)
{
String rv = "0";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Bowler.TABLE_NAME,new String[]{"count(*)"},Bowler.COLUMN_LEAGUE_ID + "=?",new String[]{leagueId},null,null,null);
if (cursor.moveToFirst()) {
rv = String.valueOf(cursor.getLong(0));
}
cursor.close();
db.close();
return rv;
}
This uses the aggregate function count to extract the number of rows for the respective league.
Note the above code is in-principle code, it has not been tested or run and may therefore have some errors.
Alternatively you could use :-
public String leagueBowlerCount(String leagueId)
{
SQLiteDatabase db = this.getReadableDatabase();
String countQuery = "SELECT * FROM " + Bowler.TABLE_NAME + " WHERE " + Bowler.COLUMN_LEAGUE_ID + " = '" + leagueId + "'";
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
db.close();
return String.valueOf(count);
}
In regard to your code :-
int count = 0;
if(null != cursor)
if(cursor.getCount() > 0){
cursor.moveToFirst();
count = cursor.getInt(0);
}
cursor.close();
Checking for a null Cursor is useless, as a Cursor returned from an SQLiteDatabase method, such as rawQuery, will never be null. Instead a valid, perhaps empty, Cursor will be returned.
Additionally checking if a Cursor has rows using the getCount method and then using moveToFirst is not needed as just using if (cursor.moveToFirst) {.....} is sufficient as if there are no rows the moveToFirst method will return false, as the move cannot be actioned.

Check if a property of a custom object ArrayList is an empty string or not?

I want to hide a WebView object (txtCode) if the code property of a custom object Arraylist (arrQues) contains nothing.
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
Its an ArrayList of custom objects fetched from a database table which is shown below
And if the code property does contains code then I have dynamically added rules to layout as shown below:
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
}
The issue is when I load the second question and so on... the layout gets messed up and the current question number does not shows as 2 even if its 2 as shown in below:
Both of these issues only arises whenever I use...
arrQues.get(count).code.isEmpty() in the code
I have also tried using "" instead of isEmpty() and even null, but the result was same.
Also what I have noticed is only those questions are loaded from database which have something in the code column.
Below is the complete code for Java file
public class QuestionsFragment extends Fragment implements View.OnClickListener {
TextView txtTimer, txtStatus;
LinearLayout boxA, boxB, boxC, boxD, mainContainer;
RelativeLayout submitContainer;
RelativeLayout.LayoutParams submit_params;
RelativeLayout.LayoutParams main_params;
ScrollView scrollView;
Button btnSubmit;
DBHelper dbHelper;
SharedPreferences sharedPreferences;
TextView txtQues;
WebView txtCode;
TextView txtOptA, txtOptB, txtOptC, txtOptD;
String ans;
ArrayList<QuestionModal> arrQues = new ArrayList<>();
ArrayList<String> arrAnswers = new ArrayList<>();
CountDownTimer countDownTimer;
boolean timerSwitch;
int selectedVal, id;
int curr_quesNo = 0;
int count = 0;
int right = 0;
int non_attempted = 0;
public QuestionsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_questions, container, false);
txtQues = view.findViewById(R.id.txtQues);
txtOptA = view.findViewById(R.id.txtOptionA);
txtOptB = view.findViewById(R.id.txtOptionB);
txtOptC = view.findViewById(R.id.txtOptionC);
txtOptD = view.findViewById(R.id.txtOptionD);
txtCode = view.findViewById(R.id.txtCode);
txtStatus = view.findViewById(R.id.txtStatus);
boxA = view.findViewById(R.id.boxA);
boxB = view.findViewById(R.id.boxB);
boxC = view.findViewById(R.id.boxC);
boxD = view.findViewById(R.id.boxD);
scrollView = view.findViewById(R.id.scrollView);
btnSubmit = view.findViewById(R.id.btnSubmit);
submitContainer = view.findViewById(R.id.submitContainer);
mainContainer = view.findViewById(R.id.mainContainer);
submit_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
main_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
sharedPreferences = getActivity().getSharedPreferences("PrefFile", MODE_PRIVATE);
timerSwitch = sharedPreferences.getBoolean("timer_switch", true);
selectedVal = sharedPreferences.getInt("selectedVal", 10);
dbHelper = DBHelper.getDB(getActivity(), sharedPreferences.getString("db_name", null));
if (!dbHelper.checkDB()) {
dbHelper.createDB(getActivity());
}
dbHelper.openDB();
String levelKey = sharedPreferences.getString("level_key", null);
arrQues = dbHelper.getQues(levelKey, selectedVal);
loadQues(timerSwitch);
txtTimer = view.findViewById(R.id.txtTimer);
switch (sharedPreferences.getString("db_name", null)) {
case "Android":
((MainActivity) getActivity()).setFragTitle("Android Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "Java":
((MainActivity) getActivity()).setFragTitle("Java Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "C":
((MainActivity) getActivity()).setFragTitle("C Quiz");
((MainActivity) getActivity()).setFragLogo(R.drawable.ic_home_black_24dp);
break;
case "C++":
((MainActivity) getActivity()).setFragTitle("C++ Quiz");
break;
case "Python":
((MainActivity) getActivity()).setFragTitle("Python Quiz");
break;
case "Kotlin":
((MainActivity) getActivity()).setFragTitle("Kotlin Quiz");
break;
}
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (timerSwitch)
countDownTimer.cancel();
if (id == 0) {
non_attempted++;
arrAnswers.add("NotAttempted");
Toast.makeText(getActivity(), "Not Attempted!", Toast.LENGTH_SHORT).show();
}
switch (id) {
case R.id.boxA:
arrAnswers.add("A");
break;
case R.id.boxB:
arrAnswers.add("B");
break;
case R.id.boxC:
arrAnswers.add("C");
break;
case R.id.boxD:
arrAnswers.add("D");
break;
}
if ((id == R.id.boxA && ans.equals("A"))
|| (id == R.id.boxB && ans.equals("B"))
|| (id == R.id.boxC && ans.equals("C"))
|| (id == R.id.boxD && ans.equals("D"))) {
right++;
count++;
Toast.makeText(getActivity(), "RIGHT!", Toast.LENGTH_SHORT).show();
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
} else {
count++;
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
}
}
});
return view;
}
public void setBtnDefault() {
boxA.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxB.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxC.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxD.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
public void sendResult() {
int attempted = selectedVal - non_attempted;
Gson gson = new Gson();
String jsonAnswers = gson.toJson(arrAnswers);
String jsonQues = gson.toJson(arrQues);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("right_key", right);
editor.putInt("wrong_key", attempted - right);
editor.putInt("total_key", selectedVal);
editor.putInt("attempted_key", attempted);
editor.putString("arr_answers", jsonAnswers);
editor.putString("arr_ques", jsonQues);
editor.commit();
((MainActivity) getActivity()).AddFrag(new ResultFragment(), 1);
}
public void LoadTimer() {
countDownTimer = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txtTimer.setText("0:" + millisUntilFinished / 1000);
}
#SuppressLint("SetTextI18n")
#Override
public void onFinish() {
txtTimer.setText("Time Over");
}
};
}
#SuppressLint("NewApi")
public void loadQues(boolean timer_switch) {
try {
id = 0;
setBtnDefault();
if (timer_switch) {
LoadTimer();
countDownTimer.start();
}
curr_quesNo++;
txtStatus.setText(curr_quesNo + "/" + selectedVal);
txtOptC.setVisibility(View.VISIBLE);
txtOptD.setVisibility(View.VISIBLE);
txtCode.setVisibility(View.VISIBLE);
main_params.removeRule(RelativeLayout.ABOVE);
submit_params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.addRule(RelativeLayout.BELOW, mainContainer.getId());
submit_params.topMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 70));
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
txtQues.setText(arrQues.get(count).ques);
txtOptA.setText(arrQues.get(count).optionA);
txtOptB.setText(arrQues.get(count).optionB);
txtOptC.setText(arrQues.get(count).optionC);
txtOptD.setText(arrQues.get(count).optionD);
txtCode.loadDataWithBaseURL(null, arrQues.get(count).code, "text/html", null, null);
if (txtOptC.getText().toString().isEmpty())
txtOptC.setVisibility(View.GONE);
if (txtOptD.getText().toString().isEmpty())
txtOptD.setVisibility(View.GONE);
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
scrollView.arrowScroll(View.FOCUS_DOWN);
}
}, 1000);
}
ans = arrQues.get(count).answer;
boxA.setOnClickListener(this);
boxB.setOnClickListener(this);
boxC.setOnClickListener(this);
boxD.setOnClickListener(this);
} catch (Exception e) {
((MainActivity) getActivity()).AddFrag(new QuestionsFragment(), 1);
}
}
#Override
public void onClick(View v) {
setBtnDefault();
id = v.getId();
v.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
public float convertDpToPx(Context context, float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
public float convertPxToDp(Context context, float px) {
return px / context.getResources().getDisplayMetrics().density;
}
}
I solved it, all issues were happening because arrQues.get(count).code was fetching null values from the database(The column "Code" had null values). As soon as I replaced null values with empty strings "" isEmpty() worked perfectly. I guess isEmpty() doesn't work with null values and is only intended for empty strings.

OnResume not showing desired result on 1sr attempt

I am new to android coding and need help with my project :
I have a function which I call from the OnResume of the mainActivity . The function reloads the data from the database and shows it on the list view .
Now when I go to second Activity and enter new data , the data is saved when onPause of secondActivity is called . On returning to mainActivity I don't see the changes made to list view but when I click on the same item of list view and go to second Activity again on returning for the 2nd time the changes start showing and the code works properly . What could be the possible reason for function not working in the 1st attempt ?
Note : I also call the function from onCreate of main Activity
EDIT 1:
the function to call
public void fill_list() {
cursor = db.rawQuery("SELECT * FROM " + GameEntry.TABLE + " WHERE " + GameEntry.G_DIFF + " = " + diff, null);
yesitis = cursor.moveToFirst();
if (yesitis)
count = cursor.getCount();
//int count=cursor.getCount();
listv = (ListView) findViewById(R.id.listview1);
listv.setAdapter(null);
arr.clear();
for (int j = 0; j < 15; j++) {
String data;
int j2 = j + 1;
data = String.valueOf(j2);
cursor3 = db.rawQuery("SELECT * FROM " + GameEntry.TABLE + " WHERE " + GameEntry.G_DIFF + " = " + diff+" AND "+GameEntry.G_LEVEL+" = "+j, null);
if (cursor3.moveToFirst()) {
cursor3.moveToPosition(0);
int showstate = cursor3.getColumnIndex(AppContract.GameEntry.G_STATE);
String temp1 = cursor3.getString(showstate);
if (temp1.equals("notStarted")) {
} else {
int showtime = cursor3.getColumnIndex(AppContract.GameEntry.time);
String temp2 = cursor3.getString(showtime);
data = data + " " + temp1 + " " + temp2;
}
}
arr.add(data);
}
ArrayAdapter<String> arradapt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arr) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = (TextView) super.getView(position, convertView, parent);
switch (diff) {
case 1:
textView.setBackgroundColor(Color.parseColor("#83EEA4"));
break;
case 2:
textView.setBackgroundColor(Color.parseColor("#00C5F6"));
break;
case 3:
textView.setBackgroundColor(Color.parseColor("#FF416A"));
break;
}
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
return textView;
}
};
listv.setAdapter(arradapt);
listv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View view, int ii, long id) {
level_select=ii;
cursor2 = db.rawQuery("SELECT * FROM " + GameEntry.TABLE + " WHERE " + GameEntry.G_DIFF + " = " + diff + " AND " + GameEntry.G_LEVEL + " = " + ii, null);
if (cursor2.moveToFirst()) {
cursor2.moveToPosition(0);
g_exist = "yes";
} else {
g_exist = "no";
}
Intent send = new Intent(ListActivity.this, GameActivity.class);
send.putExtra("level", ii);
send.putExtra("difficulty", diff);
send.putExtra("exist", g_exist);
startActivity(send);
}
});
}
onResume :
#Override
protected void onResume() {
super.onResume();
Toast.makeText(getApplicationContext(), "onResumed called", Toast.LENGTH_LONG).show();
fill_list();
}
mainActivity onCreate :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
MobileAds.initialize(this,
"ca-app-pub-6165188418561315~3404004371");
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
diff = getIntent().getExtras().getInt("difficulty");
mhelper = new appdbhelper(this);
db = mhelper.getReadableDatabase();
fill_list();
Toast.makeText(getApplicationContext(), "sqlsize =" + String.valueOf(yesitis), Toast.LENGTH_SHORT).show();
}
onPause of second activity (enterdata function updates the specified row of database ):
#Override
protected void onPause() {
super.onPause();
//Toast.makeText(getApplicationContext(), "onPause called", Toast.LENGTH_LONG).show();
timer.stop();
enterdata();
}
Thanks in advance

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

Categories