comparing array of strings to one string in android? - java

when clicking on the button it does nothing ,,,after testing I concluded the problem is with the equal method statment ,,,the whole issue is when comparing string array to string any solutions?
EditText coderead = (EditText)findViewById(R.id.editText1);
Button go = (Button)findViewById(R.id.button1);
final String mn=coderead.getText().toString();
final String code[] = {"m1","n2"};
final double pointx[] ={23.666666,65.22222};
final double pointy[] ={31.55555,29.665544};
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
for (int i=0; i<code.length; i++) {
if(code[i].equals(mn)) {
transfercode.putExtra("lat2", pointx[i]);
transfercode.putExtra("long", pointy[i]);
startActivity(transfercode);
}
else{Toast.makeText(getBaseContext(), "code not found", 5000);}
}
}
});

Your mn variable should be read after your button has been clicked.
Button go = (Button) findViewById(R.id.button1);
final String code[] = {"m1", "n2"};
final double pointx[] = {23.666666, 65.22222};
final double pointy[] = {31.55555, 29.665544};
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
// mn should be read after the button click!
EditText coderead = (EditText) findViewById(R.id.editText1);
final String mn = coderead.getText().toString();
for (int i = 0; i < code.length; i++) {
if (code[i].equals(mn)) {
transfercode.putExtra("lat2", pointx[i]);
transfercode.putExtra("long", pointy[i]);
startActivity(transfercode);
} else {
Toast.makeText(getBaseContext(), "code not found", 5000);
}
}
}
});

So if I understand your code correctly you are trying to respond to a button click and take the text that has been input and do something based on that?
You are setting the value of mn at the time you are creating the button, rather than when the button is pressed. At that time the text will be empty (or null). You should move the code to get the value of the entered text to within the onClickListener.

Should your "code not found" message happen outside the for loop?

What do you mean by nothing happens? Do you get a Toast message or not? Did you make sure that no error is being generated? If you are not getting the Toast Message and you have no errors, then make sure the intent is correct. I would recommend you debug the code from the line of Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
Then, report what is happening back here.

Something I don't get. With these two lines:
final String mn=coderead.getText().toString();
final String code[] = {"m1","n2"};
Why don't you just compute the (final) index to code right then and there, vs waiting until onClick?

Related

Using setOnLongClickListener to setText on multiples of buttons

I am trying to change the text on a button after setOnLongClickListener amd there are six buttons to choose from. Currently, regardless of which button I click, the list button is updated with the new text.
I think I have tried everything on this thread:
setonlongclicklistener for several buttons at once
Eventually i hope to save these new button values to shared preferences so they are there when the app is next started.
public class MainActivity extends AppCompatActivity {
private Button btn;
Context context;
final String[] task = new String[1];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
Resources r = getResources();
String pName = getPackageName();
String PREFERENCES_FILE_KEY = "com.example.buttondemo";
String SECURE_PREFS_FILE_KEY = "com.example.buttonnames";
// Declare shared preferences
SharedPreferences sharedPreferences = this.getSharedPreferences(PREFERENCES_FILE_KEY, Context.MODE_PRIVATE);
// get shared preferences for each button and apply the stored name to each button
//String buttonText = sharedPreferences.getString("Value01", "Button_01");
for (int i=1;i<=6;i++) {
String buttonId = "button" + i;
btn = (Button) findViewById(r.getIdentifier(buttonId, "id", pName));
btn.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
task[0] = showAddItemDialog(MainActivity.this, btn);
//sharedPreferences.edit().putString(buttonId, task[0]).apply();
return true;
}
});
}
}
private String showAddItemDialog(Context context, Button btnNew) {
final EditText taskEditText = new EditText(context);
taskEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
final String[] task = new String[1];
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Enter New button value")
.setMessage("Enter New button value:")
.setView(taskEditText)
.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
task[0] = String.valueOf(taskEditText.getText());
btnNew.setText(String.valueOf(taskEditText.getText()));
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
return task[0];
}
}
Thanks.
What's happening is the btn variable is getting reassigned each iteration of your loop. Therefore once the long click listener fires, you are calling showAddItemDialog(this, btn) where btn is holding a reference to whatever it was set to in the last loop iteration (when i = 6).
So the behaviour you're experiencing makes sense. Hopefully this is enough to point you in the right direction.
As a side note, finding views based on dynamic ids that come from r.getIdentifier() might be a bit of a bad design choice and could open up bugs in the future. I would recommend simplifying it to just use R.id.button1, R.id.button2 etc. if possible.

Beginner - Syntax to concatenate a variable within a findViewById and within a string or textview assignment

I'm new to android programming with very little experience, I'll try ask the correct question but I apologize if some of my understanding isn't quite up to scratch.
I'm building a basic calculator app with buttons 0 to 9. The user can use these to input that specific number into a text field.
I have the same piece of code (below) to do my button action for all 0 to 9 buttons. Just where to see the number 1 it's replaced with that buttons relevant number.
Button button1 = (Button) findViewById(R.id.button_calc_1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String number_1 = ("1");
TextView Insert_Number_1 = (TextView ) findViewById(R.id.editTextoutput);
TextView Insert_Number_1_view = (TextView) findViewById(R.id.CurrentDisplay);
Insert_Number_1.append(number_1);
Insert_Number_1_view.append(number_1);
}
});
So i'm writing a subroutine of the same code that I can then call upon for the relevant button.
public String numberbuttons(String value){
Button button1 = (Button) findViewById(R.id.button_calc_1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String number_1 = ("1");
TextView Insert_Number_1 = (TextView ) findViewById(R.id.editTextoutput);
TextView Insert_Number_1_view = (TextView) findViewById(R.id.CurrentDisplay);
Insert_Number_1.append(number_1);
Insert_Number_1_view.append(number_1);
}
});
}
Bear in mind this is a work in progress.
My question is basically how do I add the variable numberbuttons to the button_calc_(insert numberbuttons here)
EDIT:
Okay so from the second block of code. I want to use the numberbuttons variable within the findViewById(R.id.button_calc_1).
So in my head I picture it like this.
findViewById(R.id.button_calc_+(numberbuttons);
The same for when I call a textview. I picture it like this.
TextView Insert_Number_+(numberbuttons) = (TextView ) findViewById(R.id.editTextoutput);
The findViewById() method requires an integer, not a String, so you cannot just pass in a String with the name of the button that you are trying to use. When you use R.id.xxx you are passing a reference to the resource, which is actually just an int.
To accomplish what you want I suggest using a list of some type to store the buttons, and then looping through this. Please see an example below.
ArrayList<Button> buttons = new ArrayList<>();
buttons.add((Button) findViewById(R.id.button1)); //Do this for all the buttons.
for(Button b : buttons){
b.setText("1"); //Do whatever you need to each button in here.
}
If you wanted to use a method to manage all your buttons, you can do this too!
changeButton((Button) findViewById(R.id.button1));
private void changeButton(Button b){
//Change the button
}
EDIT:
To be more relevant to your question if I understand correctly, to add an event handler to each.
ArrayList<Button> buttons = new ArrayList<>();
buttons.add((Button) findViewById(R.id.button1)); //Do this for all the buttons.
for(int i = 0; i < buttons.size(); i++){
Button b = buttons.get(i);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String number = String.valueOf(i);
TextView Insert_Number_1 = (TextView ) findViewById(R.id.editTextoutput);
TextView Insert_Number_1_view = (TextView) findViewById(R.id.CurrentDisplay);
Insert_Number_1.append(number_1);
Insert_Number_1_view.append(number_1);
}
});
}

get/use radio button value android

I FIGURED OUT WHAT I WAS DOING. I HAD THE VARIABLE NAME IN QUOTES WITH THE REST OF THE URL STRING.
How do you save the value of a Radio button into a variable and use that variable later.
I can see the variable Day_Item in my LogCat and the value is in there but when try using Day_Item later it does not show the valuable.
Below is a section of my code that shows the buttons.
String Day_Item = null;
public class SearchDB extends Activity {
private static final String TAG = "MyApp";
String start_log = "STARTED";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
final RadioButton radio_monday = (RadioButton) findViewById(R.id.monday);
radio_monday.setOnClickListener(radio_listener);
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long arg3)
{
int id = parent.getId();
if (spinner2_count2 < spinner2_count1 ) {
spinner2_count2++; }
else
{
String city_spinner_log = "CITY SPINNER";
Log.d(TAG, city_spinner_log);
String item = cityspinner.getSelectedItem().toString();
String nameContentType = "name";
String cityURL = "GetRestaurant.php?day=Day_Item&city=" + item;
Log.d(TAG, cityURL);
String shop_data = DataCall.getJSON(cityURL,nameContentType);
Log.d(TAG, shop_data);
Bundle bundle = new Bundle();
bundle.putString("shopData", shop_data);
Intent myIntent = new Intent(SearchDB.this, ShowRestaurant.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0);
}
}
}
//ONCLICKLISTENER that saves RADIO value into a variable.
public OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Day_Item = (String) rb.getText();
Log.d(TAG,Day_Item);
Toast.makeText(SearchDB.this, Day_Item, Toast.LENGTH_SHORT).show();
}
};
}
You would need a bit more code to get a good solid answer. Such as how is Day_Item allocated? And is it's scope global? Are you calling it from another activity or the one it's allocated within? These are just guesses at this point:
1) Are you sure your onClickListener isn't firing multiple times? Thus setting Day_Item to an undesired text or nothing at all?
2) Rather a question/answer,
"but when try using Day_Item later it does not show the valuable"
I'm assuming this means that it is null? Well if it's being set properly, and then it is being null'd... it either is being explicitly null'd by you somewhere (such as (1)) or else the allocation and scope are the issue area I believe...

How do I get this string array to pass over to the next class and be used

This is kind of hard to explain. Basically it's kind of like a simple game. I want the people to input their names (currently the submit button is not working correctly) hit submit for each name and when all names are in they hit play. It then opens up the next class. It needs to get the string array from the prior class as well as the number of players. It then needs to select each persons name in order and give them a task to do (which it randomly generates). Then it allows the other people to click a button scoring how they did. (I am not sure how to set up the score system. Not sure if there is a way to assign a score number to a particular array string) I would then like it after 5 rounds to display the winner. If you have any input or could help me out I would be extremely grateful. Thanks for taking the time... here are the two classes i have.
Class 1
public class Class1 extends Activity
{
int players=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < players; i++)
{
names[i] = input.getText().toString();
input.setText("");
}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Class2.class);
done.putExtra("players", players);
done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Class 2
public class Class2 extends Activity
{
int players, counter, score, ptasks,rindex;
String[] names, tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class2);
Intent game = getIntent();
players = game.getIntExtra("players", 1);
names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks[0]= "task1";
tasks[1]= "task2";
tasks[2]= "task3";
tasks[3]= "task4";
tasks[4]= "task5";
tasks[5]= "task6";
tasks[6]= "task7";
tasks[7]= "task8";
tasks[8]= "task9";
tasks[9]= "task10";
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
}
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
//not sure what to put here to get the scores set up
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
//not sure what to put here to get the scores set up
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
//not sure what to put here
}
});
counter++;
}
}
I'm sure this thing is riddled with errors. And I'm sorry if it is I'm not that well experienced a programmer. Thanks again
You can pass a string array from one activity to another using a Bundle.
Bundle bundle = new Bundle();
bundle.putStringArray("arrayKey", stringArray);
You can then access this stringArray from the next activity as follows:
Bundle bundle = this.getIntent().getExtras();
String[] stringArray = bundle.getStringArray("arrayKey");
I'm not sure if this is the only thing you intend to do. I hope it helps. Also, to assign a score to a particular string array, assuming your scores are int's you could use a HashMap as follows,
HashMap<String[],int> imageData = new HashMap<String[],int>();
But I'm not sure how you would pass this Map to another activity if you intend to do so.
http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String,%20java.lang.String[])
Use this cheat:
In Class2, convert you array string (tasks) to string (strSavedTask)by adding "|" separator. After that, pass your strSavedTask into Bundle and start to Class1.
When return to Class1, read strSavedTask from Bundle, split it by "|".
That's my cheat to pass array between 2 activity ^^
Hope this way can help you!

Array List transfering correctly & Setting a score to each array list member

To all you that have helped me with my other questions thank you. I almost have it, but 2 final problems are preventing it from working the way i want.
These 2 classes are supposed to do as follows. 1st class gets the names of the people that want to play the game. Uses the same EditText and when they input their name they click submit. When all the names are submitted they click the done/play button which sends them and their data (how many players and names) to the next class. On class 1 i believe the error lies in the submit button. I'm trying to add all the names to an array list and I dont believe it is doing it correctly. When I run the app it takes in the names just fine from the users standpoint. But on the following screen it should display their name: (it says null so it is not getting the names correctly) and a task to do (which it does correctly).
The last thing it needs to do is on class 2 it needs to allow those buttons (failed, champ, and not bad) to only need to be clicked once (then it sets a score to the name of the person who's turn it was) and then it needs to start the next person and task. (It does neither atm). I would really appreciate help getting this blasted thing to work. Thanks to all who take the time to reply. And sorry if ur sick of seeing my help requests.
Class 1
public class Class1 extends Activity
{
int players=0, i=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
final ArrayList<String> names = new ArrayList<String>();
//names = new String[players];
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
//for( i=i; i < players; i++)
//{
players++;
names.add(input.getText().toString());
//names[i] = input.getText().toString();
input.setText("");
//}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Game.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("arrayKey", names);
done.putExtra("players", players);
//done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Game Class
public class Game extends Activity
{
int players, counter=0, score, ptasks,rindex;
String[] names;
String[] tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
Intent game = getIntent();
players = game.getIntExtra("players", 1);
//names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks = new String[10];
tasks[0]= "";
tasks[1]= "";
tasks[2]= "";
tasks[3]= "";
tasks[4]= "";
tasks[5]= "";
tasks[6]= "";
tasks[7]= "";
tasks[8]= "";
tasks[9]= "";
names = new String[players];
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
return;
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
return;
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
return;
}
});
}
counter++;
}
}
}
As a side note. The things that you see within those sections that have // comments next to them I have there because i was testing out between those and the ones that arent commented out and neither worked. If you have any input on fixing any of this i appreciate it.
I see two problems with your code that might explain why you get a null for your players list in your second Activity:
In Game, String[] names = bundle.getStringArray("arrayKey"); should be
ArrayList<String> names = bundle.getStringArrayList("arrayKey");`
In Class1, you're putting the ArrayList into the Bundle(bundle.putStringArrayList("arrayKey", names);) which is pointless since bundle goes no where. You should be putting it into the Intent instead:
done.putStringListExtra("arrayKey", names);
Note that your code is all the more confusing because you have both a String [] named names and an ArrayList named names in different scopes. Decide on one (I'd recommend the List) and get rid of the other.
Also, in Game, this is unncessary:
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
Intent game = getIntent();
players = game.getIntExtra("players", 1);
You already have the bundle just before this, so you could as well do:
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
players = bundle.getInt("players", 1);
The basic concept is that from the calling activity, you put information into an Intent using the various putExtra() and putExtraXXX() methods. In the called activity, you get the information you had put into the Intent by either
getting a Bundle *from * the Intent via getExtras() and then getting everything put in using the various get() methods on the Bundle (not the Intent).
directly invoking the getExtraXXX() methods on the Intent.
For the second part, as your code currently stands, it simply going to loop over all the players immediately (5 times in all, I don't understand the purpose of counter).
What you should instead be doing is performing all of your processing (calculating the score for the current player, incrementing the value of the player index, setting the next task etc) only when one of the 3 buttons is pressed. If it's going to be a long-lived task, you could disable the buttons until finished in order to enforce the requirement of allowing only one button to be pressed per player. Re-enable the buttons when the next player is ready.
I don't have the energy to churn out everything you need but at a starting point, turn this:
public void onCreate(Bundle savedInstanceState)
{
//...other code here
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
return;
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
return;
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
return;
}
});
}
counter++;
}
//...other code here
}
into
public void onCreate(Bundle savedInstanceState)
{
//...other code here
int i = 0;
TextView name1 = (TextView) findViewById(R.id.pname);
TextView task = (TextView) findViewById(R.id.task);
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
//do what must be done for the current player, calculate score, etc
prepareNextPlayer(++i, names, name1, task);
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
//do what must be done for the current player, calculate score, etc
prepareNextPlayer(++i, names, name1, task);
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
//do what must be done for the current player, calculate score, etc
prepareNextPlayer(++i, names, name1, task);
}
});
//...other code here
}
private void prepareNextPlayer(int i, ArrayList<String> names, String [] tasks, TextView nameField, TextView taskField)
{
if(i >= names.size())
{
//all players have been processed, what happens now?
return;
}
int rindex = generator.nextInt(10);
nameField.setText( names.get(i)+":");
task.setText( tasks[rindex]);
}

Categories