我一直在努力寻找为什么我的LeagueId现在不被传递回上一个活动的原因,而且我似乎无法弄清楚。我浏览了许多不同的帖子,寻找有关解决问题的想法,但似乎找不到任何相关的内容。
我正在尝试将LeagueId传递回列表视图,以显示特定礼帽和联赛的系列赛列表。我要传回BowlerId,而不是LeagueId。当我调试该应用程序时,我可以看到应该被故意传递回去的变量已被填充,但是当它返回到上一个活动时,它没有被拾取。
这是设置意图的代码:
//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);
}
});
这是我上一个活动的代码:
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());
}
}
在此方面提供的任何帮助将不胜感激。如果需要其他任何条件,请告诉我,我将非常乐意提供。
这是我修改后的“取消按钮代码”:
//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);
}
});
“取消”按钮的图像:
工作取消按钮代码:
//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) {
}
答案 0 :(得分:2)
您的SettingsActivity
没有将leagueId
发送到SeriesActivity#onActivityResult()
,因为SeriesActivity
在启动SettingsActivity
时没有请求结果。
您应该使用SettingsActivity
而不是startActivityForResult()
启动startActivity()
。之后,您可以通过使用setResult()
中的SettingsActivity
进行设置来返回结果。请参阅here。
注意:您不应弄乱Android的生命周期-不应在super.onResume()
中调用onCreate()
。