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