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.
Related
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
}
I am stuck in a situation. I'm trying to use spinners in order for users to select locations. I am populating the spinners via sqlite. The idea is sometimes there is a country, province, city and sub-areas, however any field can be blank (if not populated in database).
I would like the spinners to be "hidden" if they do not have the values stored in the database. However, only the "next step down" (ex: country to province) is hidden and not all the "other steps down" (city and sub-area)
I hope I am being clear enough, if not I can clarify.
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
if (parent.getId() == R.id.spinner_query_country)
{
country.selected = (class_location)country.spinner.getSelectedItem();
get_province();
}
else if (parent.getId() == R.id.spinner_query_province)
{
province.selected = (class_location)province.spinner.getSelectedItem();
get_city();
}
else if (parent.getId() == R.id.spinner_query_city)
{
city.selected = (class_location)city.spinner.getSelectedItem();
get_sub_area();
}
else if (parent.getId() == R.id.spinner_query_sub_area)
{
sub_area.selected = (class_location)sub_area.spinner.getSelectedItem();
}
}
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
void get_country()
{
make_spinner(country, db.getAll("SELECT * FROM country"));
}
void get_province()
{
make_spinner(province, db.getAll("SELECT * FROM province WHERE country_key=" + country.selected._key));
}
void get_city()
{
make_spinner(city, db.getAll("SELECT * FROM city WHERE province_key=" + province.selected._key));
}
void get_sub_area()
{
make_spinner(sub_area, db.getAll("SELECT * FROM sub_area WHERE city_key=" + city.selected._key));
}
void make_spinner(_structure structure, List<class_location> location_list)
{
if (location_list.size() > 0)
{
class_location location_array[] = location_list.toArray(new class_location[location_list.size()]);
ArrayAdapter<?> adapter = new ArrayAdapter<Object>(this, android.R.layout.simple_spinner_item, location_array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
structure.spinner.setAdapter(adapter);
structure.spinner.setVisibility(View.VISIBLE);
structure.textview.setVisibility(View.VISIBLE);
}
else
{
structure.spinner.setAdapter(null);
structure.spinner.setVisibility(View.GONE);
structure.textview.setVisibility(View.GONE);
}
}
You are hidding only one spinner, not all of them simply because you are setting the visibility at make_spinner() and you only check one step down on your onItemSelected(if else strict). To make it clear, your code sets the visibility or invisibility of the components on a method that is never called for the "others steps down".
P.S.: Your code is kinda messy and do not follow the conventions or guidelines of Android. This is bad. Try to checkout some guidelines, help your collaborators :)
I think this is really easy but I am fairly new to android development so thanks in advance
If the first one is checked I generate a random number for text Item 1. If both the checkboxs are checked I generate text for the second text. I was wondering what is the most efficient way to do this
Here is the snippet that I need help with
if(edit1.isChecked()){
text1.setText(String1[randomInt]);
}
if(edit1.isChecked() && edit2.isChecked()){
text2.setText(String1[randomInt]);
}
Obviously, the first statement will show true in both. basically is there a way to say if edit2 is false?
Try this:
edit2.isChecked()=false;
if(edit1.isChecked() && (edit2.isChecked()==false)) {
text2.setText(String1[randomInt]);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v.findViewById(R.id.chkSelected);
TextView tv = (TextView) v.findViewById(R.id.tvName);
// pi = (PackageInfo) arg0.getItemAtPosition(position);
cb.performClick();
if (cb.isChecked()) {
studentList.add(tv.getText().toString());
} else if (!cb.isChecked()) {
studentList.remove(tv.getText().toString());
}
}
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"))
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