I'm currently trying to add a condition based on what the user has selected on the drop down. If the first item is selected, then the data entered on the textView will be multiplied by 34, else the second item will be multiplied by 18. So far I can test the first selection works as it should, but it's not picking up the second selection. Could anybody explain to me the proper way to tackle this conditional? this is what my code looks like.
public class CatalinaFerryTickets extends AppCompatActivity{
String[] ferryRoutes = new String[]{"To Catalina Island", "To Long Beach"};
private Button renderBtn;
EditText handleData;
TextView displayData;
#Override
protected void onCreate(Bundle savedInstanceState) {
// RENDER SPINNER TO DEVICE
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalina_ferry_tickets);
final Spinner spin=findViewById(R.id.mySpinner);
final ArrayAdapter<String> myAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, ferryRoutes);
spin.setAdapter(myAdapter);
renderBtn=findViewById(R.id.button);
displayData=findViewById(R.id.textView);
displayData.setMovementMethod(new ScrollingMovementMethod());
renderBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleData=findViewById(R.id.editInput);
int ticketAmount = Integer.parseInt(handleData.getText().toString());
int total;
// FAULTY CONDITIONAL STATEMENT
if (ferryRoutes[0] == "To Catalina Island"){
total = ticketAmount * 34;
displayData.setText(Integer.toString(total));
}
else{
total = ticketAmount * 18;
displayData.setText(Integer.toString(total));
}
}
});
}
}
You aren't checking what's selected, you're checking what the value is in a static array. So it will always take one branch. If you want to do something based on the spinner selection, you need to actually query the spinner for what's selected.
The problem here is that the ferryRoutes array is never linked to a drop-down component.
Because of that, the condition
if (ferryRoutes[0] == "To Catalina Island")
will always be true, and the else block will never be executed.
Also, never compare String(s) using the reference equality operator (==). Use equals
if ("To Catalina Island".equals(ferryRoutes[0]))
You might be lucky to have the String(s) interned, and that would make the equality operator work. But don't do that as a general rule.
Related
So, let's say I have an Array:
String Array[] = {"Dog goes woof", "Cat goes meow", "Cow goes moo", "Etc..."};
And I have a Button and a TextView connected so that when the button is pressed I can say for example:
public void onClick(View v) {
TextView.setText(Array[1]);
}
Which will then fill the TextView with "Cat goes meow". But I now want the button to decided what should fill the TextView based on what's already there. So let's say I have Array[0] displayed in the TextView, so that it says "Dog goes woof". I then want an if-test that recognizes that Array[0] is displayed, and then changes it to, say, Array[2]. And if Array[2] is displayed, it will then change it to Array[1], and so on.
I am having a bit of issues on how I should set up this if-test, and how I should phrase it so that it recognizes what it is I am looking for in the TextView. And I do want to look for Array[X] or Array[Y] and not the strings themselves like "Dog goes woof". Basically something that says (warning: poor seudo-code ahead):
if TextView contains Array[X]
then TextView.setText(Array[Y])
else if TextView contains Array[Y]
then TextView.setText(Array[Z])
else TextView.setText(Array[X])
I easily understood your requirement and here's what you need:
final Button yourButton= findViewById(R.id.yourButtonID);
final String Array[] = {"Dog goes woof", "Cat goes meow", "Cow goes moo", "Etc..."};
final TextView yourTextView = findViewById(R.id.yourTextViewID);
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = 0;
if(textView.getText() == null)
{
textView.setText(Array[1]); // initial value
}
else{
for(int i=0;i<Array.length;i++){
if(Objects.equals(textView.getText(),Array[i])){
position=i; //got the selected position
break;
}
}
if(position<Array.length-1){
textView.setText(Array[position+1]);
}
else{
textView.setText(Array[position-1]);
}
}
}
});
This will check whether there is an initial value and in case of one then it will check for the selected position and if the position is less than the last item then it will increment one and if the last item is selected it will decrement one.
I've tested it and it's working, still something feel free to ask.
If my question is unclear, please let me know, I am quite new in this area.
I did the following:
I freezed and optimized tensorflow model
It is a RNN lstm model , getting a sentence then saying if that positive or negative
I successfully added all the things in android studio
Now I have a editbox to enter my sentence , then touch Run button, then this run button should fill the label if this sentence was positive or negative,
Would you please give me some instructions that if there is a predefined function I should use,
or I have to write down that by myself, if this is the case, how,
Thanks in advance for helping.
Update
This is something I have tried but it seems quite incorrect:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inferenceInterface = new TensorFlowInferenceInterface();
inferenceInterface.initializeTensorFlow(getAssets(), MODEL_FILE);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final EditText editNum1 = (EditText) findViewById(R.id.editNum1);
inferenceInterface.fillNodeInt(INPUT_NODE, INPUT_SIZE, editNum1);
inferenceInterface.runInference(new String[] {OUTPUT_NODE});
int[] resu = {0, 0};
inferenceInterface.readNodeInt(OUTPUT_NODE, resu);
final TextView textViewR = (TextView) findViewById(R.id.txtViewResult);
textViewR.setText(Float.toString(resu[0]) + ", " + Float.toString(resu[1]));
}
});
}
Edit2
there is FillNodeInt in TensorFlowInferenceInterface,
what I thought is that, it is going to tie my input in the editbox to the input node in my model,
so the first parameter is input node, the second is the size, and the third should be the input for example I fill in the text box,
but there is no function to have the third parameter as String,
they are int or float or byte(like example above which is Int), or something like buffer
can someone please explain which method I can use
I am running this on an emulator: 5554:Nexus_5_API_22_x86.
I am trying to learn SharedPreferences and have written a simple test program.
It contains two buttons: one adds a String + random # to a set which will be stored in SharedPreferences, and the other prints the contents of that set.
Whenever I press the square button on the bottom right hand of the screen and press 'x' to close the app window, then relaunch the app, the contents of the set are reset - in other words, printing the set yields nothing.
However, if I exit the app using only the back button, the contents remain - in other words, printing the set yields whatever was in it before.
Java:
...
public class MainActivity extends AppCompatActivity
{
final int PREF_MODE_PRIVATE = 0;
TextView output;
Set<String> testSet;
Random randomGenerator = new Random();
SharedPreferences data;
SharedPreferences.Editor dataEditor;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output = (TextView) findViewById(R.id.textView); //getting the output textfield
data = getPreferences(PREF_MODE_PRIVATE);
//If first-time setup has not been completed, execute the following block
//I don't want the String Set to be reset to empty every time the app is launched
if(data.getBoolean("initialized", false) == false)
{
//Adding the empty set to storage
testSet = new HashSet<String>();
dataEditor = data.edit();
dataEditor.putStringSet("testSet", testSet); //Add the empty Set to storage
dataEditor.putBoolean("initialized", true); //Set initialized flag to true
dataEditor.apply();
}
}
public void printTestSet(View view)
{
output.setText(""); //Clears the text field
Set<String> toBePrinted = data.getStringSet("testSet", null); //Gets the String Set
//Prints content of the String Set
if(toBePrinted != null)
{
for(String word : toBePrinted)
{
output.append(word + '\n');
}
}
}
public void addToTestSet(View view)
{
//Generate a string followed by a random number and add it to the String Set
int randomInt = randomGenerator.nextInt(1000);
data.getStringSet("testSet", null).add("NEW STRING #" + randomInt);
}
}
The button that prints the String Set calls printTestSet and the one that adds a String to the Set calls addToTestSet.
Upon creation, the app uses a simple boolean to check if it has been initialized the for the first time. If not, it adds an empty String Set to storage and sets the boolean to true. If the boolean is already true (meaning it has already added the empty string set), that step is skipped.
You need to either commit your data either realtime (where you are doing apply) or in application life cycle handler onpause (when your app goes to background). Use option 1 when you have little data or 2 when you have large amount of data to commit.
It looks like you're not saving the shared preferences in addToTestSet.
When you do getStringSet and then add, you need to again save the string Set back into shared prefs like you do in your onCreate() using dataEditor.apply().
Or if you want to be a bit more efficient, you can save your stringSet in the activity's onPause() method to prevent constantly writing to SharedPrefs
When you hit back, your app process isn't being killed, which means when you open it up again the Android system is restoring whatever it can (what was written in textViews, checkboxes that were checked, etc. simple things like that). What you see in the box might not actually be getting populated by SharedPrefs.
Lets say you have an object like this and you want to have the program go through each dynamically created Checkbox to see if it has not been checked.
If has not been checked, then the program should create a notification alerting the user that one or more of these objects has not been checked.
What is the best way to have the program identify whether the checkbox is checked or not?
Each time I run the program, it only applies to the last created Checkbox regardless of how many checked or unchecked checkboxes proceed it.
Thank you for your time.
View ObjectView;
CheckBox check;
//A whole bunch of code here.
public void onClick(View arg0) {
if (check==null){
}
else if (check==null || check.isChecked()){
}
else {
ObjectView.getId();
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getActivity())
.setSmallIcon(android.R.drawable.stat_notify_more)
.setContentTitle("Items missing")
.setContentText("One or more items are missing");
int ID_Notify = 01;
getActivity();
NotificationManager managenote = (NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
managenote.notify(ID_Notify, mBuilder.build());
Im gonna help you with an example of my code and try to explain it, aware that im not gonna babysit you (means you cant just copy paste) because i still have some work to do.
First, a new dynamic spinner will be created everytime you click a button (inside onClick) :
Spinner spinner = new Spinner(this);
spinner.setAdapter(spinChildAdapter);
parentSpinner.addView(spinner);
spinner.setId(totalDynamicChild); //the spinner's id will be the increment from 0
spinnderIdList.add(totalDynamicChild); //list of the dynamic spinner ID
totalDynamicChild++;
Then, we can access those dynamic Spinners with :
for(int i = 0; i < totalDynamicChild; i++)
{
Spinner s = (Spinner)findViewById(spinnderIdList.get(i));
//do something with the spinner's object here
}
Feel free to comment if you have some questions.
me again, iv tried following the android checkbox example, and whilst it has worked the most part, i need the code to only be initiated when a button is clicked, there is only one button in the program and this button is also used to do the maths calcs.
I think i would need a nested if statement, but im just wondering if any of you guys could help me with the construction of this, when the checkBox is checked, i would like it to check if there is data in the text field next to the checkbox, if there is data i would like the program to bring up an error statement, although this is only to be done once the calculation button has been called on.
can anyone give me any help on constructing this, i have tried adding listeners but i already have one on the calc button and if i add more into this method, i get error messages :/
There are three checkboxes, all used to check different field, however i also only want one checkbox to be checked at any one time and only if there is no data in the text field that applies to this.
cheers guys, sorry if im a bit vague but im starting to loose my rag with my lack of knowledge.
cheers
public class Current extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current);
// Show the Up button in the action bar.
setupActionBar();
Button calc1 = (Button)findViewById(R.id.current_calculate);
calc1.setOnClickListener(new View.OnClickListener() {
CheckBox checktime = (CheckBox) findViewById(R.id.custom1);
CheckBox checkcurrent = (CheckBox) findViewById(R.id.custom2);
CheckBox checkcharge = (CheckBox) findViewById(R.id.custom3);
public void onClick(View v) {
//i would like this part to check that checktime is checked and that there is no data in editText Time1
if (((CheckBox) v).isChecked()) {
Toast.makeText(Current.this,
"Bro, try Android :)", Toast.LENGTH_LONG).show();
}
//i would like this part to check that checkCurrent is checked and that there is no data in editText current1
if (((CheckBox) v).isChecked()) {
Toast.makeText(Current.this,
"Bro, i mean it ", Toast.LENGTH_LONG).show();
}
//i would like this part to check that checkCharge is checked and that there is no data in editText charge1
if (((CheckBox) v).isChecked()) {
Toast.makeText(Current.this,
"Bro, try Android :)", Toast.LENGTH_LONG).show();
}
// please note that i have not yet added the current.text field yet as i cannot be bothered with it throwing up errors just yet, please bear
// in mind that i will be doing another two sums on this program, the next sum will be current1 / time1 and then the next will be charge1/current1
// any help would be much appreciated, for now i only want the program to check that EditText current1 is empty and if so do the calculation bellow
EditText Charge1 = (EditText)findViewById(R.id.number_input_2);
EditText Time1 = (EditText)findViewById(R.id.number_input_3);
TextView Distances_answer = (TextView)findViewById(R.id.Distances_answer);
double charge = Double.parseDouble(Charge1.getText().toString());
double time = Double.parseDouble(Time1.getText().toString());
//Time is a class in Java
Distances_answer.setText("" +charge*time);
}
});
}
First of all as it is onclicklistener for a button, v would always be button in your case. So ((CheckBox) v).isChecked() would give runtime error. Change that to checktime.isChecked() or any other checkbox you would like to check its checked status. As for checking the emptyness of editext it can be done by edittext.getText().toString().isEmpty()
public void onClick(View v) {
//i would like this part to check that checktime is checked and that there is no data in editText Time1
if(Time1.length()==0){
checktime.setChecked(true);
Toast.makeText(Current.this,
"Bro, try Android :)", Toast.LENGTH_LONG).show();
}
//i would like this part to check that checkCurrent is checked and that there is no data in editText current1
if(current1.length()==0){
checkCurrent.setChecked(true);
Toast.makeText(Current.this,
"Bro, i mean it ", Toast.LENGTH_LONG).show();
}
//i would like this part to check that checkCharge is checked and that there is no data in editText charge1
if(charge1.length()==0){
checkCharge.setChecked(true);
Toast.makeText(Current.this,
"Bro, tryAndroid ", Toast.LENGTH_LONG).show();
}
// please note that i have not yet added the current.text field yet as i cannot be bothered with it throwing up errors just yet, please bear
// in mind that i will be doing another two sums on this program, the next sum will be current1 / time1 and then the next will be charge1/current1
// any help would be much appreciated, for now i only want the program to check that EditText current1 is empty and if so do the calculation bellow
// EditText Charge1 = (EditText)findViewById(R.id.number_input_2);
// EditText Time1 = (EditText)findViewById(R.id.number_input_3);
// TextView Distances_answer = (TextView)findViewById(R.id.Distances_answer);
double charge = Double.parseDouble(Charge1.getText().toString());
double time = Double.parseDouble(Time1.getText().toString());
//Time is a class in Java
Distances_answer.setText("" +charge*time);
}
});
Just make sure that you findviewbyid all the edit texts before the button click.