Variable and test if fail - android

I am using the following code to grab the selected value in the spinner:
cbFormato.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v, int posicao, long id) {
//pega nome pela posição
formatoSelecionado = parent.getItemAtPosition(posicao).toString();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
When I use the code below to show the value that he took the spinner returns the value: Circular
The code to return value of spinner:
Toast.makeText(AppTubulao.this, "Circular: " + formatoSelecionado, Toast.LENGTH_LONG).show();
The problem is when I test the value of the spinner in the same code below it does not recognize the value, ie the value Circular he shows me in Toast is not the same as the "Circular" if that is the test
if (formatoSelecionado == "Circular")
{
Toast.makeText(AppTubulao.this, "Circular: " + formatoSelecionado, Toast.LENGTH_LONG).show();
}
He did not enter the if statement

Assuming they really are set to the same value, the following should evaluate to true.
if (formatoSelecionado.equals("Circular")) {

String equality in Java should use either the equals or equalsIgnoreCase methods. Thus, to test of formatoSelectionado is equal to the string "Circular" you need to use:
if (formatoSelecionado.equals("Circular")) ...
or
if (formatoSelecionado.equalsIgnoreCase("Circular"))

Related

Can't use an array for switch case

I have an array created in my strings file(in values folder).
Now i want to use it for choosing on spinner, using switch case.
something like that:
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_dropdown_item_1line,workers);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
public void addUser(View view) {
switch (Arrays.toString(workers)){
case workers[0]: //this option isn't compiling
Waiter waiter = new Waiter();
waiter.setName(editName.getText().toString());
waiter.setLast(editLast.getText().toString());
waiter.setPass(editPass.getText().toString());
name = editName.getText().toString();
last = editLast.getText().toString();
passId = Integer.parseInt(editPass.getText().toString());
break;
case workers[1]:
break;
}
and so on..
EDIT:
tried now with if statement, this method should add me new workers on button press, but after that when i press the button nothing happens:
public void addUser(View view) {
if(Arrays.toString(workers).equals(workers[0])) {
Waiter waiter = new Waiter();
SQLiteDatabase usersDB = openOrCreateDatabase("USERES_DATABSE.sqlite", MODE_PRIVATE, null);
usersDB.execSQL("CREATE TABLE IF NOT EXISTS users_table (name TEXT, last TEXT, pass INTEGER)");
waiter.setName(editName.getText().toString());
waiter.setLast(editLast.getText().toString());
waiter.setPass(editPass.getText().toString());
name = editName.getText().toString();
last = editLast.getText().toString();
passId = Integer.parseInt(editPass.getText().toString());
if (editName.getText().toString().isEmpty() ||
editLast.getText().toString().isEmpty() ||
editPass.getText().toString().isEmpty()) {
AlertDialog alertDialog = new AlertDialog.Builder(UserCreatingActivity.this).create();
alertDialog.setTitle("Oops,");
alertDialog.setMessage("You forgot to fill something");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
} else {
usersDB.execSQL("INSERT INTO users_table VALUES('" + name + "','" + last + "','" + passId + "')");
AlertDialog alertSucsess = new AlertDialog.Builder(UserCreatingActivity.this).create();
alertSucsess.setTitle("Congrats,");
alertSucsess.setMessage(name + " " + last + " Has been created");
alertSucsess.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
alertSucsess.show();
}
usersDB.close();
// ADDING SHIFT MANAGER
} else if (Arrays.toString(workers).equals(workers[1])){
You can not use variables in a switch. Change to if.
Or you can change to case 0:, case 1:, case 2: since it's always workers[]
case expressions must be constant values.
If possible values of workers are predefined, use these predefined and constant values as case expressions, instead.
A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings)
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
You can't make the cases variables. The switch is fine as is. Just change the cases to constants.
If this is unworkable then you must do as Alex advises and resort to if statements, which in many cases result in fewer lines of code.
For example
if (Arrays.toString(workers).equals(workers[0])) {
Waiter waiter = new Waiter();
waiter.setName(editName.getText().toString());
waiter.setLast(editLast.getText().toString());
waiter.setPass(editPass.getText().toString());
name = editName.getText().toString();
last = editLast.getText().toString();
passId = Integer.parseInt(editPass.getText().toString());
}
I think there is an error in your logic but can't be more specific without more code.
As everyone mentioned you cannot use arrays with the switch so you are going for the if. And the way you have written condition seems incorrect if(Arrays.toString(workers).equals(workers[0])). After going through question then based on the selection in the spinner you have to add user...correct me if I am wrong. So first you need to find the value of spinner.
Solution1
Create a instance String variable and implement onItemSelected as follows.
String workerSelected;
//your code
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
workerSelected=worker[position]
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
OR
Since you have added spinner.setOnItemSelectedListener(this); then just directly override method i.e following code is enough
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
workerSelected=worker[position]
}
And then inside addUser method you can for if condition as
if(workerSelected.equals(worker[0])){
//your code
}else if(workerSelected.equals(worker[1])){
//your code
}
Solution2
Directly inside your addUser method
String workerSelected = spinner.getSelectedItem().toString();
if(workerSelected.equals(worker[0])){
//your code
}else if(workerSelected.equals(worker[1])){
//your code
}

Getting String from Spinner, and using it on conditional statements

I have this program that will change the hours and minutes of the values I get from Calendar.
So I'm changing only the hour, I'm doing a Timezone thing here. So, what I do is I make an array of the TimeZones at Strings.xml and put it on a spinner. And then, when I change the item on the spinner, I set the text of a textview to the selected value on the spinner.
I can do it up to here.
My problem lies in the conditional statements. I have a button that gets the text in the TextView and I will use that in my If statements. This is my Syntax.
This gets me the values from the Spinner to the TextView.
Spinner TimezoneSelect = (Spinner)findViewById (R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.timzones, R.layout.support_simple_spinner_dropdown_item);
TimezoneSelect.setAdapter(adapter);
//final String SelectedTimeZone = TimezoneSelect.getSelectedItem().toString();
TimezoneSelect.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TimeZoneStatus = parent.getItemAtPosition(position).toString();
TimeZoneDisplay.setText(TimeZoneStatus);
And this is the faulty If statement.
public void onClick(View v) {
// TODO Auto-generated method stub
int newhour;
String TimeZoneNow = TimeZoneStatus.trim().toString();
String Jakarta = "UTC+7:00 (Jakarta)";
if ((TimeZoneNow == "UTC+7:00(Jakarta)") || (TimeZoneNow == Jakarta))
//^lol desperate code
{
newhour = hour - 1;
TimeText.setText(newhour + ":" + minutes);
}
}
});
Help! :c
try this way
if(TimeZoneNow.equals(Jakarta)
used .equals() method for string comparison
use this code
if ((TimeZoneNow .equalsIgnoreCase(Jakarta))
//^lol desperate code
{
newhour = hour - 1;
TimeText.setText(newhour + ":" + minutes);
}
Try this:
In your case replace == with eqauls().
Explanation:
== operator is used to compare reference.
equals() is used to compare content.

Spinner Android (SetPrompt)

I am running into an issue with a spinner that I defined and bound to an array resource. The problem is that it "ONLY" defaults to the first item of the array when it is first constructed. I am using the setPrompt and it looks like it is being ignore totally. I wrote to the log and I can see in the log that I am setting it to the right value but it instead keeps defaulting to the first element in the array.
_spnCountDown.setPrompt(setting);
Log.d("SETTING_SPINNER", setting);
_spnCountDown.setOnItemSelectedListener(new OnItemSelectedListener()
{
boolean _firstTime = true;
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3)
{
if (_firstTime == false)
{
String value = _spnCountDown.getSelectedItem().toString();
MobileAppManager.getInstance().storeSetting("CountDown",
value);
Log.d("SETTING_SPINNER onItemSelected", value);
}
else
{
Log.d("SETTING_SPINNER onItemSelected", "Ignore");
_spnCountDown.setPrompt(Settings.this.getInitialCountDown());
_firstTime = false;
}
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
I have followed few answers that recommend using a flag to overcome the fact that onSetItemSelected will first the first time the spinner is constructed. So, rightfully so, I am ignoring the first call. However as I mentioned, It is defaulting to first entry.
So, If this line will not do anything _spnCountDown.setPrompt("5 seconds")
I'm not sure but if I understand your question correctly this suggests perhaps you should use setSelection?
Setting default values in spinner in android

Android Gallery visible ImageView is null?

I want to draw a check mark for the image view I click on and uncheck the imageview I clicked on before using the following code snip. I store last checked position in mDeviceAdapter. When I try to uncheck old position, the image view always gives null even for the partial visible image view. I am really confused because I thought only invisible one is recycled... Newbie in Android and any comment is appreciated.
public void CheckableImageView#setChecked(boolean checked) {
if (mChecked != checked) {
mChecked = checked;
invalidate();
}
}
mDeviceGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckableImageView viewToCheck = (CheckableImageView) view;
if (!viewToCheck.isChecked()) {
int oldCheckedPosition = mDeviceAdapter
.getCheckedPosition();
mDeviceAdapter.setCheckedPosition(position);
View checkedView = mDeviceGallery
.getChildAt(oldCheckedPosition);
Log.d(TAG, "old position="+oldCheckedPosition + "old view="+checkedView);
if (checkedView != null) {
((CheckableImageView) checkedView)
.setChecked(false);
Log.d(TAG, "uncheck position="
+ oldCheckedPosition);
}
viewToCheck.setChecked(true);
That's not the right approach.
You need to add to your data type a boolean field (i.e mIsChecked).
On the onItemClick method set the value of that variable to true and keep its INDEX as a member of the adapter. When another item is clicked set the value of that item to true and set the value of the saved one to false (change the value of the datatype in you ArrayList in the INDEX you stored in the previous click).
Now, in the getView() method, you must have if/else statement. Something like:
if (item.isChecked())
{
checkedView.setChecked(true);
}
else
{
checkedView.setChecked(false);
}
Example to the onClick method: (just a general direction)
if (item.isChecked())
{
checkedView.setChecked(false);
yourList.get(position).setChecked(true);
yourList.get(mLastCheckedIndex).setChecked(false);
mLastCheckedIndex = position;
notifyDataSetChanged();
}
else
{
//same but opposite.
}
Hope this helps!

Spinner onItemSelected a Action should trigger in for getting data

I am trying this code
findUsStateOrMileSpinnerState.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view,
int i, long l)
{
spinnerState = findUsStateOrMileSpinnerState.getSelectedItem().toString();
if(spinnerState.equalsIgnoreCase("State")){
getDetailsState();
}
if(spinnerState == "Miles"){
getDetailsMiles();
}
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
}
);
On some selected item it should call another listener.
Spinner is having Miles and State.
But it is not going through the if statement, am I doing something wrong.
Looking forward to your reply.
thanks.
Did you try using the eqauls() method for comparing two strings in your code instead of == operator ?
if (spinnerState.equals("Miles") {
getDetailsMiles();
...
}
Check this out plz : http://www.java-samples.com/showtutorial.php?tutorialid=221
Try using the getSelectedIndex() instead of getSelectedItem(). You have to be sure you always get "State" and "Miles" at specified index.
You should do string compare via equals and not spinnerState == "Miles"
Try using equalsIgnoreCase or equals instead of using == to compare strings

Categories

Resources