Retrieve Spinner Selected Item To Use in Condition Statement - java

I'm able to save my spinner selected item states. I'm just having trouble sending and retrieving selected items to use in if statement in next activity.
I know I must use sharedpreferences, but I'm having a bit trouble when it comes to spinner items.
Here's my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
LastSelectedItem = getSharedPreferences("PriorSelected", MODE_PRIVATE);
go_back_btn = (Button) findViewById(R.id.go_back_btn);
themeSpinner = (Spinner) findViewById(R.id.themeSpinner);
go_back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LastSelectedItem = getSharedPreferences("PriorSelected", MODE_PRIVATE);
SharedPreferences.Editor editor = LastSelectedItem.edit();
editor.apply();
Intent intent = new Intent(getApplicationContext(), home.class);
startActivity(intent);
}
});
int LastSelection = LastSelectedItem.getInt("LastSelection", 0);
editor = LastSelectedItem.edit();
ArrayAdapter<CharSequence> themeAdapter = ArrayAdapter.createFromResource(settings.this, R.array.theme_array, android.R.layout.simple_spinner_item);
themeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
themeSpinner.setAdapter(themeAdapter);
themeSpinner.setSelection(LastSelection);
themeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
editor.putInt("LastSelection", position).apply();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}

SharedPreferences settings = getSharedPreferences("app_pref", 0);
SharedPreferences.Editor editor = settings.edit();
themeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//To save
editor.putInt("position",position);
editor.commit();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//To retrieve in next activity
SharedPreferences settings = getSharedPreferences("app_pref", 0);
int snowDensity = settings.getInt("position", -1); //0 is the default value
instead of share preference you can store value to int and pass it to next activity.
int position=-1;
themeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
position=position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
position=-1;
}
});
go_back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), home.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
Second Activity:
int position= getIntent().getIntExtra("position", -1);

It's fine, I found the answer.
// send data to next activity
go_back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int Myposition = themeSpinner.getSelectedItemPosition();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("LastSelection", Myposition);
editor.apply();
Intent intent = new Intent(getApplicationContext(), home.class);
startActivity(intent);
Below is code to retrieve on next activity:
// Retrieve and implement conditional statement
private void ToggleTheme() {
final SharedPreferences LastSelectedItem = getApplicationContext().getSharedPreferences("PriorSelected", Context.MODE_PRIVATE);
int LastSelection = LastSelectedItem.getInt("LastSelection", 0);
if (LastSelection == 1) {
homebutton.setBackgroundResource(R.drawable.light_theme_buttons);

Related

I can't open a chat Intent by pressing a button

I can't open a new Intent by a button but only in listview I followed a guide but it solved it listview and I need a normal click where is the problem in my code
The code only works with the listview...
buttonadd.setOnClickListener(new AdapterView.OnClickListener(){
#Override
public void onClick(AdapterView<?> parent, View view, int postition, long id){
String curentgruopname = parent.getItemAtPosition(postition).toString();
Intent groupchatintent = new Intent(MainActivity.this , buttonaddactivity.class);
groupchatintent.putExtra("groupname", curentgruopname);
startActivity(groupchatintent);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int postition, long id) {
String curentgruopname = parent.getItemAtPosition(postition).toString();
Intent groupchatintent = new Intent(MainActivity.this , buttonaddactivity.class);
groupchatintent.putExtra("groupname", curentgruopname);
startActivity(groupchatintent);
}
});
Maybe it works when you initialize the OnClicklistener in the OnCreate Method.
Here is an Example:
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
button = findViewById(R.id.button);
button.setOnClickListener(buttonClick);
}
View.OnClickListener buttonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(testActivity.this, nextActivity.class);
startActivity(intent);
}
};

Keep the data save in sharedPreference although pressed back button - Android Studio

I have some problem as I mention in my question. I have two activity, Activity A and Activity B. When I Enter some data in Activity A, then I press next button, it will redirect to Activity B. At Activity B, I also enter some data. When I press back button, the data at Activity A is display as I entered before. When I press next button, the data that I entered at Activity B is missing. Below is my SharedPreferences code.
Activity A:
public class NewSuggestion extends AppCompatActivity {
private EditText etYear, etMonth, etTitle, etOwnValue;
private RadioGroup rgSuggestWill;
private RadioButton radioButton;
private Button btnNext;
ArrayAdapter<CharSequence> adapter;
private Spinner spReviewer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etTitle = findViewById(R.id.etTitle);
etYear = findViewById(R.id.etYear);
etMonth = findViewById(R.id.etMonth);
rgSuggestWill =findViewById(R.id.rgSuggestWill);
final Calendar c = Calendar.getInstance();
String mm = c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US);
int yy = c.get(Calendar.YEAR);
etYear.setText(new StringBuilder().append(yy));
etMonth.setText(new StringBuilder().append(mm));
spReviewer = findViewById(R.id.spReviewer);
adapter = ArrayAdapter.createFromResource(this,R.array.reviewer,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spReviewer.setAdapter(adapter);
spReviewer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("title",etTitle.getText().toString());
editor.putString("year",etYear.getText().toString());
editor.putString("month",etMonth.getText().toString());
// get selected radio button from radioGroup
int selectedId = rgSuggestWill.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = findViewById(selectedId);
editor.putString("suggestionwill",radioButton.getText().toString());
if (spReviewer.getSelectedItem().toString().equals("Please choose")){
AlertDialog alertDialog = new AlertDialog.Builder(NewSuggestion.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Please choose your reviewer");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}else{
editor.putString("reviewer",spReviewer.getSelectedItem().toString());
Intent intent = new Intent(NewSuggestion.this,NewSuggestion2.class);
startActivity(intent);
}
editor.apply();
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent(NewSuggestion.this, DashboardApp.class);
startActivity(intent);
}
}
Activity B:
public class NewSuggestion2 extends AppCompatActivity {
private EditText etPresent, etDetails, etBenefit;
private ImageView imgAttach,btnCamera,btnGallery;
private Button btnNext,btnClear;
private Intent intent;
private Bitmap bitmap;
private int REQUEST_CODE = 1;
public static final int RequestPermissionCode = 1 ;
public static final String DEFAULT = "N/A";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion2);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION (Cont..)");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
imgAttach = findViewById(R.id.imgAttach);
btnCamera=findViewById(R.id.btnCamera);
EnableRuntimePermission();
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
btnGallery=findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Photo"),REQUEST_CODE);
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
Intent intent = new Intent(NewSuggestion2.this,ConfirmSuggestion.class);
startActivity(intent);
}
});
btnClear = findViewById(R.id.btnClear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgAttach.setImageBitmap(null);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 7 && resultCode == RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
imgAttach.setImageBitmap(bitmap);
}
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri uri = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imgAttach.setImageBitmap(bitmap);
}catch (IOException e){
e.printStackTrace();
}
}
}
public void EnableRuntimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(NewSuggestion2.this,
Manifest.permission.CAMERA))
{
Toast.makeText(NewSuggestion2.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(NewSuggestion2.this,new String[]{
Manifest.permission.CAMERA}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(NewSuggestion2.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(NewSuggestion2.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
break;
}
}
#Override
public void onBackPressed() {
}
}
Assign value to present,details,benefit from sharedpref
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
etPresent.setText(sharedPref.getString("present", ""));
etDetails.setText(sharedPref.getString("details", ""));
etBenefit.setText(sharedPref.getString("benefit", ""));
In Activity B make sure you save data in onBackPressed()
#Override
public void onBackPressed() {
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
super.onBackPressed();
}
You have to override the onBackPress() method.In Activity B it is necessary to put data in to SharedPreferences.
#Override
public void onBackPressed() {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.commit();
}

Get IndexOutOfBoundsException: Index: 1, Size: 1 When Clicking on Row

I had this working in the past, but I made some changes to my code and now, whenever I delete a row from the ListView and click on one of the remaining rows, I am getting IndexOutOfBoundsException: Index: 1, Size: 1.
This only seems to be happening when there is a single row remaining. If there are more than one row remain, this error does not appear.
The image above shows that the when there are more than one row remaining the error does not occur.
I am not sure why this would be happening since none of the code for selecting and deleting a row has changed.
I have checked other posts on this site but none of them seem to be similar to what I am experiencing.
Android IndexOutOfBoundsException: Index: 1, Size: 1
OutOfBoundException index:1, size:1
java jtable removeRow : java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
I have posted my code below.
Logcat:
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.get(ArrayList.java:411)
at ca.rvogl.tpbcui.views.LeagueAdapter$2.onClick(LeagueAdapter.java:116)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Code for selecting a row in the listview:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
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.getBaseScore());
holder.basescorepercentage.setText(league.getBaseScorePercentage());
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:
((MainActivity) context).showLeagueDialog(true, leaguesList.get(position), position);
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) {
int leagueId = leaguesList.get(position).getId();
Intent myIntent = new Intent(context, BowlerActivity.class);
myIntent.putExtra("leagueId", leagueId);
context.startActivity(myIntent);
}
});
}
Code for deleting a row:
//Deleting League From SQLite Database And Removing The League Item From The List By Its Position
public void deleteLeague(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 League From The Database
db.deleteLeague(leaguesList.get(position));
//Removing League From The List
leaguesList.remove(position);
mAdapter.notifyItemRemoved(position);
toggleEmptyLeagues();
}
});
snackbar.show();
}
The error seems to be happening with this line int leagueId = leaguesList.get(position).getId();
Any help getting this error fixed would be greatly appreciated.
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().getIntExtra("leagueId",2));
leagueId = findViewById(R.id.tvLeagueId);
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);
}
});
mAdapter = new BowlerAdapter(this, bowlersList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
//recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
recyclerView.setAdapter(mAdapter);
toggleEmptyBowlers();
}
//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(leagueId, bowlerName, bowlerAverage);
//Get The Newly Inserted Bowler From The Database
Bowler n = db.getBowler(leagueId);
if (n != null) {
//Adding New Bowler To The Array List At Position 0
bowlersList.add( 0, n );
//Refreshing The List
mAdapter.notifyDatasetChanged(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();
}
//Opens Dialog With Edit/Delete Options
private void showActionsDialog(final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
View view = View.inflate(this, R.layout.dialog_options_1, null);
final AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(new ContextThemeWrapper(BowlerActivity.this, R.style.AppTheme));
alertDialogBuilderUserInput.setView(view);
alertDialogBuilderUserInput.setCancelable(true);
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
//Cancel
final ImageButton cancel_btn = (ImageButton) view.findViewById(R.id.cancel);
cancel_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
alertDialog.cancel();
}
});
//Edit
ImageButton edit_btn = (ImageButton) view.findViewById(R.id.edit);
edit_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showBowlerDialog(true, bowlersList.get(position), position);
alertDialog.dismiss();
}
});
ImageButton delete_btn = (ImageButton) view.findViewById(R.id.delete);
delete_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Bowler will be deleted.", Snackbar.LENGTH_LONG)
.setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteBowler(position);
}
});
snackbar.show();
alertDialog.dismiss();
}
});
Window window = alertDialog.getWindow();
window.setGravity(Gravity.TOP);
alertDialog.show();
}
//Show Alert Dialog With EditText Options to Enter/Edit A League
//When shouldUpdate = true, It Will Automatically Display Old Bowler Name And Change The Button Text To UPDATE
public void showBowlerDialog(final boolean shouldUpdate, final Bowler bowler, final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
final View view = View.inflate(this, R.layout.dialog_bowler, null);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(new ContextThemeWrapper(BowlerActivity.this, R.style.AppTheme));
alertDialogBuilderUserInput.setView(view);
alertDialogBuilderUserInput.setCancelable(true);
leagueId.setText(savedLeagueId);
final EditText inputBowlerName = view.findViewById(R.id.etBowlerNameInput);
TextView dialogTitle = view.findViewById(R.id.dialog_title);
dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_bowler_title) : getString(R.string.lbl_edit_bowler_title));
if (shouldUpdate && bowler != null) {
leagueId.setText(bowler.getLeagueId());
inputBowlerName.setText(bowler.getName());
}
alertDialogBuilderUserInput
.setCancelable(false)
.setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
})
.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
dialogBox.cancel();
}
});
ImageView bowlerName = (ImageView) view.findViewById (R.id.ivBowlerName);
bowlerName.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder bowlerName = new AlertDialog.Builder(BowlerActivity.this);
bowlerName.setMessage("Enter the name of the bowler to hold your new scores.");
bowlerName.setCancelable(true);
bowlerName.create();
bowlerName.show();
}
});
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
alertDialog.getButton( AlertDialog.BUTTON_POSITIVE).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
//Show Toast Message When No Text Is Entered
if (TextUtils.isEmpty(inputBowlerName.getText().toString())) {
Snackbar.make( view, "Enter Bowler Name", Snackbar.LENGTH_LONG )
.setAction( "Action", null ).show();
return;
} else {
alertDialog.dismiss();
}
//Check If User Is Updating Bowler
if (shouldUpdate && bowler != null) {
//Updating Bowler By Its Id
updateBowler(inputBowlerName.getText().toString(), position);
} else {
//Creating New Bowler
createBowler(leagueId.getText().toString(), inputBowlerName.getText().toString());
}
}
});
}
//Toggling List And Empty Bowler View
private void toggleEmptyBowlers() {
//You Can Check bowlerList.size() > 0
if (db.getBowlersCount() > 0) {
noBowlersView.setVisibility( View.GONE);
} else {
noBowlersView.setVisibility( View.VISIBLE);
}
}
#Override
public 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);
}
}
This is the line that it is complaining about. This worked perfectly before I move the onClick() to the adapter.
savedLeagueId = String.valueOf(getIntent().getIntExtra("leagueId",2));
I am really hoping that someone can help me get this issue resolved. I have tried several different approaches from other stackoverflow posts and I am still not able to resolve it.
mAdapter.notifyItemRemoved(position);
Means that the adapter will shift and animate items up. However, the items will not be redrawn.
You can observe that by clicking on the last item of your list after deleting any item: you should see the same crash.
And by clicking on any item after the one you deleted (except the last one), the details view should show the next item instead of the one you clicked.
The issue is that position is no longer relevant, because the indices have changed. Instead use the value for leagueId that you already have in your binder. Simply remove the int leagueId that is shadowing the String leagueId and that should work as expected.
The problem is that the view was already bind and the position at this method:
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int leagueId = leaguesList.get(position).getId(); // here position will still be 1 after deletion
//...
}
});
belongs to the old index. To fix it, use the same object you fot previously.
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int leagueId = league.getId(); //league object will be the same
//...
}
});
****Try This****
#Override
protected void onBindViewHolder(#NonNull final BoardsViewHolder holder, final int position, #NonNull final Board model) {
holder.setTitle(model.getBoardTitle());
holder.setDesc(model.getBoardDesc());
holder.setDate(model.getCreatedOn());
holder.mDeleteBoardButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setTitle("Delete Board");
alert.setMessage("This Board will be deleted forever");
alert.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final ProgressDialog loading = new ProgressDialog(mContext);
loading.setMessage("Deleting...");
loading.show();
getSnapshots().getSnapshot(position).getReference().delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
notifyDataSetChanged();
loading.dismiss();
}else {
loading.dismiss();
Toast.makeText(mContext,"Something went wrong please try again later",Toast.LENGTH_LONG).show();
}
}
});
}
});
alert.setNegativeButton("Keep", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
});
This is the problem of zero based elements. Your code is trying to access an non existing element index. Launch your app in debug mode and line by line see what is happening. Android studio has an excellent debugger built-in, so it is very easy to go step by step and see what is happening with your variables.

spinner value not passing from one activity to another

ViewToken.class:
spinnerGenre = (Spinner) findViewById(R.id.spinnerGenres);
spinnerGenre1 = (Spinner) findViewById(R.id.spinner);
docname = spinnerGenre1.getSelectedItem().toString();
session = spinnerGenre.getSelectedItem().toString();
next=(Button)findViewById(R.id.button4);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next=new Intent(ViewToken.this,Tokens.class);
next.putExtra("docname", docname.toString());
next.putExtra("session", session.toString());
startActivity(next);
}
});
Tokens.class
Intent i2 = getIntent();
final String docname = i2.getStringExtra("docname");
final String session = i2.getStringExtra("session");
The spinner value from ViewToken.class is not passed to Tokens.class
Change this in ViewToken.class
next.putExtra("docname", docname);
next.putExtra("session", session);
You can do the following in your Tokens.class
Bundle extras = getIntent().getExtras();
String docname = extras.getString("docname");
String session = extras.getString("session");
The calls to getSelectedItem() should be made in the onClick listener so that it gets the most up-to-date values selected.
So instead the onClick() method will be:
#Override
public void onClick(View v) {
docname = spinnerGenre1.getSelectedItem().toString();
session = spinnerGenre.getSelectedItem().toString();
Intent next=new Intent(ViewToken.this,Tokens.class);
next.putExtra("docname", docname);
next.putExtra("session", session);
startActivity(next);
}
It is likely that the calls to getSelectedItem() where being made before anything was selected and therefore the values being put() inside the intent where incorrect.
get the values from the spinners just before send them.
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
docname = spinnerGenre1.getSelectedItem().toString();
session = spinnerGenre.getSelectedItem().toString();
Intent next=new Intent(ViewToken.this,Tokens.class);
next.putExtra("docname", docname.toString());
next.putExtra("session", session.toString());
startActivity(next);
}
});
int positionOfSelectedDataFromSpinner;
iv.putExtra("position", positionOfSelectedDataFromSpinner);
Create a New Method
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
positionOfSelectedDataFromSpinner= i;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
And In Second Activity
int positionToShowToSpinner = iv.getIntExtra("position",0);
spinner.setSelection(positionToShowToSpinner);

Displaying Spinner selected item in another class TextView

So I have a Spinner and I wan't user to select one item from it and then display his selection in another activity.. but Button won't even do anything.. I'm guessing error is in intent.putExtra of int position == 0.. can somebody help me out?
cilj = (Spinner) findViewById(R.id.spinnerPrehranaCilj);
prikaziRezultat = (Button) findViewById(R.id.buttonPrehranaPrikaziRezultate);
ArrayAdapter<CharSequence> ciljPrehranaSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.spinner_cilj_prehrana, android.R.layout.simple_spinner_item);
ciljPrehranaSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cilj.setAdapter(ciljPrehranaSpinnerAdapter);
prikaziRezultat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cilj.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0){
Intent intent = new Intent(getApplicationContext(), AppLayoutMain.class);
intent.putExtra("ciljJePovecanjeTezine", cilj.getItemIdAtPosition(0));
startActivity(intent);
} else if (position == 1){
Toast.makeText(PrehranaInputMain.this, "drugo bi trebalo bit odabrano", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
});
This is the second activity
String prehrana = intent.getStringExtra("ciljJePovecanjeTezine");
ciljPrehranaRezultat = (TextView) findViewById(R.id.textViewPrehranaCiljRezultat);
ciljPrehranaRezultat.setText(prehrana);
Thank you!!
Here's the modified code of first activity:
cilj = (Spinner) findViewById(R.id.spinnerPrehranaCilj);
prikaziRezultat = (Button) findViewById(R.id.buttonPrehranaPrikaziRezultate);
ArrayAdapter<CharSequence> ciljPrehranaSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.spinner_cilj_prehrana, android.R.layout.simple_spinner_item);
ciljPrehranaSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cilj.setAdapter(ciljPrehranaSpinnerAdapter);
cilj.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0){
Toast.makeText(PrehranaInputMain.this, R.string.cilj_prehrana_nista_odabrano, Toast.LENGTH_SHORT).show();
} else if (position == 1){
Intent intent = new Intent(getApplicationContext(), AppLayoutMain.class);
intent.putExtra("ciljJePovecanjeTezine", cilj.getSelectedItem().toString());
startActivity(intent);
} else if (position == 2){
Intent intent = new Intent(getApplicationContext(), AppLayoutMain.class);
intent.putExtra("ciljJeMrsavljenje", cilj.getSelectedItem().toString());
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
prikaziRezultat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
and second activity
String prehrana = intent.getStringExtra("ciljJePovecanjeTezine");
String prehrana2 = intent.getStringExtra("ciljJeMrsavljenje");
ciljPrehranaRezultat = (TextView) findViewById(R.id.textViewPrehranaCiljRezultat);
ciljPrehranaRezultat.setText(prehrana);
// SEEMS LIKE SOME IF STATEMENT NEEDED HERE?
//ciljPrehranaRezultat.setText(prehrana2);
your listener to the drop down is not set until the user clicks the button, which means until you click the button at least once, selecting an item from the drop down doesn't do anything.
have you tried to select an item from the spinner after you click the button?
if you want to go to the other activity when the user clicks the button, keep only the startActivity(intent) in the onClick() method and move the onItemSelected() method up a level, move the intent as a global variable.
cilj = (Spinner) findViewById(R.id.spinnerPrehranaCilj);
prikaziRezultat = (Button) findViewById(R.id.buttonPrehranaPrikaziRezultate);
Intent intent = new Intent(getApplicationContext(), AppLayoutMain.class);
ArrayAdapter<CharSequence> ciljPrehranaSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.spinner_cilj_prehrana, android.R.layout.simple_spinner_item);
ciljPrehranaSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cilj.setAdapter(ciljPrehranaSpinnerAdapter);
cilj.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0){
intent.putExtra("ciljJePovecanjeTezine", cilj.getItemIdAtPosition(0));
} else if (position == 1){
Toast.makeText(PrehranaInputMain.this, "drugo bi trebalo bit odabrano", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
prikaziRezultat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
}
});
also, even in that case, it appears to me that you are only jumping to the activity when the user selects item at position "0". can we assume this is not a blank space and your spinner only has 2 entries in it?
Change the following lines:
if (position == 0){
Intent intent = new Intent(getApplicationContext(), AppLayoutMain.class);
intent.putExtra("ciljJePovecanjeTezine", (CharSequence)cilj.getItemIdAtPosition(0));
startActivity(intent);
} else if (position == 1){
Toast.makeText(PrehranaInputMain.this, "drugo bi trebalo bit odabrano", Toast.LENGTH_SHORT).show();
}
To:
Intent intent = new Intent(getApplicationContext(), AppLayoutMain.class);
intent.putExtra("ciljJePovecanjeTezine", cilj.getItemAtPosition(position));
startActivity(intent);

Categories

Resources