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
}
Related
I have a problem to set a new value in my ListView after I saved it in the sharedPreferences.
On the picture you can see what I can see on my smartphone screen (easier to describe for me). If I press now the Item "Korrektur-Faktor" an AlertDialog opens and i can set a new Value.
If I now press save the new value (80) will be saved in the SharedPreferences but the value in the second Line of my ListViewItem will not be automatically updated.
Here some code:
String secLineCorrect = correctvalue.toString();
ValueSettings targetValue = new ValueSettings("Zielwert", "getTargetSharedPref"); //TODO
ValueSettings correctFactor = new ValueSettings("Korrektur-Faktor", secLineCorrect + " mg/dl pro 1IE");
//Füllen der ListView
final ArrayList<ValueSettings> valuesSettingsList = new ArrayList<>();
valuesSettingsList.add(targetValue);
valuesSettingsList.add(correctFactor);
final ValueSettingsListAdapter valuesSettingsAdapter = new ValueSettingsListAdapter(this, R.layout.settings_list_item_two_lines, valuesSettingsList);
lvValues.setAdapter(valuesSettingsAdapter);
//Klickbare Items
lvValues.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
//First Item in List
case 0:
Toast.makeText(SettingsActivity.this, "You clicked on: " + valuesSettingsList.get(position).getFirstLine() + "mit Item Nummer" + position, Toast.LENGTH_SHORT).show();
break;
//Second Item in List
case 1:
AlertDialog.Builder mBuilder = new AlertDialog.Builder(SettingsActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_correctfactor,null);
final EditText mCorrectFactor = (EditText) mView.findViewById(R.id.et_correct_factor_input);
Button mCancel = (Button) mView.findViewById(R.id.btn_cancel);
Button mSave = (Button) mView.findViewById(R.id.btn_save);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.show();
//Click on Cancel
mCancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Toast.makeText(SettingsActivity.this, "Abgebrochen. Kein neuer Wert eingespeichert!", Toast.LENGTH_SHORT).show();
}
});
//Click on Save
mSave.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(mCorrectFactor.getText().length() > 0){
correctvalue = Integer.parseInt(mCorrectFactor.getText().toString());
editor.putInt(correctValueKEY, correctvalue);
editor.commit();
Toast.makeText(getApplicationContext(), "1 IE entspricht " + correctvalue + " mg/dl.", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), "Wert ist auf " + correctvalue + " md/dl gesetzt. Keine Änderung vorgenommen.", Toast.LENGTH_LONG).show();
}
dialog.cancel();
}
});
break;
}
}
});
As you can see I set the text in the beginning of the code. So every time I want that the new value I saved before is shown up, I have to go back into my main-Activity and start the settings-Activity new. But now I want that after i pressed save and the AlertDialog is closed, the new value is shown. I tried so much but never get a solution.
May someone can help me out :)
First you should make sure the saved value is reflected in the valuesSettingsList, as suggested by woodii.
You can then add this line after you save the new value:
valuesSettingsAdapter.notifyDataSetChanged();
For such features i can suggest PreferenceFragment or PreferenceActivity.
Anyway you can use SharedPreferences.OnSharedPreferenceChangeListener and override the method onSharedPreferenceChanged and update the Entry in the list accordingly.
Currently you only change the stored value in the SharedPreferences but not the visible value in the List.
I searched the web, but couldn't find a solution. I found several codes but I have some problems to implement it in my code. Hope you guys know what I'm messing up here.
I'm creating an SMS app, where you choose from a spinner (which preloads
a txt) and you can continue the text from an edittextfield and press
the button to send the SMS. Working great but now I would like the toast to
contain what the user wrote in the field.I can create a normal Toast where I can write my own text. If you look at case 1 you can see where I wrote value_edittextfield (just so you can see where the value should be) and String nrforanvandare is the EditTextField.
I really hope there is a solution, because it would be so awesome.
spinneruse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0 :
skickatelBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}
);
case 1 :
skickatelBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsgnruta = tele1txt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
String nrforanvandare = nrrutaforspinner.getText().toString();
sendMsg(theNumberr, myMsgnruta + nrforanvandare);
Toast.makeText(getActivity(), "value_Edittextfield. sent",
Toast.LENGTH_LONG).show();
}
}
);
break;
According to EditText you can use getText() to get the input text, which in turn returns Editable, which you can get with the default toString() method.
For example:
Toast.makeText(getApplicationContext(), myEditText.getText().toString(),
Length_LONG).show();
Here, I assumed that your EditText variable name is myEditText.
This should do it.
EDIT:
On a side note, why wouldn't using String nrforanvandare = nrrutaforspinner.getText().toString(); do the trick, given nrrutaforspinner is your EditText? If not, well, that's how you do it.
i am trying to write some sort of code, which adds two numbers the user puts in, this is my code:
l.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i= Integer.parseInt(l.input1.getText().toString());
int j= Integer.parseInt(l.input2.getText().toString());
int sum = i+j;
l.result.setText(sum);
}
});
for some reason the emulator just collapse, i am new to this all, and am really greatfull for any help. THANK YOU.
setText() of TextView either accepts a String value as parameter to display or a integer value which is a string resource id that you have described in res/values/strings.xml
The integer value you passing is a real value and you have make the TextView to understand it as real value and not a String resource reference. So convert the integer to String and then set the value inside text view.
Solution:
l.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i= Integer.parseInt(l.input1.getText().toString());
int j= Integer.parseInt(l.input2.getText().toString());
int sum = i+j;
l.result.setText(String.valueOf(sum));
}
});
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.
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"))