Android Studio Button command - java

I've created a string which is a random string from an array. The user presses a button and the function executes again, showing the user a new string from the array.
This is what I have thus far, which doesn't quite work:
String[] letters = {"s", "a"};
String randomSad = (letters[new Random().nextInt(letters.length)]);
tv1 = (TextView) findViewById(R.id.textview11);
tv1.setText(randomSad);

Always provide the code that you have already tried. But this being a simple implementation, it should look like this :
String[] nameList = {"Sam", "Harry", "Ron"}; //Store the list as you like
int index i = 0;
//put the correct id of the TextView from the xml file
TextView nameTextView = (TextView) findViewById(R.id.nameTextView);
//put the correct id of the Button from the xml file
Button button = (Button) findViewById(R.id.button1);
//set the OnclickListener and define what you want to happen in the onClick() method
button.setOnClickListener(new OnclickListener() {
nameTextView.setText(nameList[index]); //set the name in the index as text
if((index+1) >= nameList.length)
index++; //increase the index by 1, for the next time.
else
index = 0; // to loop back to the first name.
});
If you want the last name to stay even if the butten is pressed again, cut out the else part.
Edit :
()After you provided the code
String[] letters = {"s", "a"};
String randomSad = (letters[new Random().nextInt(letters.length)]);
tv1 = (TextView) findViewById(R.id.textview11);
tv1.setText(randomSad);
button.setOnClickListener(new OnclickListener() {
randomSad = (letters[new Random().nextInt(letters.length)]);
tv1.setText(randomSad); //set the name in the index as text
});

Related

How do I output an integer to an EditText view?

I have an EditText as input. I am trying to use it for output as well. I've tried the following:
FoodIncomeCounter.setText(TotalFood.getText().toString());
FoodIncomeCounter = Integer.parseInt(TotalFood.getText());
String FoodIncomeCounter = String.valueOf(TotalFood);
and nothing works. For the 1st and 2nd option the "getText()" cannot be resolved. Am I able to output to an EditText view, or do I need to make a separate TextView and output to that? Hopefully that all makes sense to you. My goal is to be able to use the FoodCampX and FoodUpgradeX variables to calculate the income and output that into FoodIncomeCounter variable/EditText view (which currently you can manually input). FoodIncomeCounter is an EditText view, FoodCampX and FoodUpgradeX and FoodIncome are integers, TotalFood is an integer. Thank you for teaching me.
Here is the code:
//to get from user input and into variable form
FoodIncomeCounter = (EditText) findViewById(R.id.FoodIncomeCounter);
IncomeSubmitButton = (Button) findViewById(R.id.IncomeSubmitButton);
FoodCamp1Counter = (EditText) findViewById(R.id.FoodCamp1Counter);
FoodCamp2Counter = (EditText) findViewById(R.id.FoodCamp2Counter);
FoodCamp3Counter = (EditText) findViewById(R.id.FoodCamp3Counter);
FoodUpgrade1Counter = (EditText) findViewById(R.id.FoodUpgrade1Counter);
FoodUpgrade2Counter = (EditText) findViewById(R.id.FoodUpgrade2Counter);
FoodUpgrade3Counter = (EditText) findViewById(R.id.FoodUpgrade3Counter);
FoodCampSubmitButton = (Button) findViewById(R.id.FoodCampSubmitButton);
}
//Buttons
public void onClick(View v) {
switch (v.getId()) {
case R.id.IncomeSubmitButton:
//reset to value
FoodIncomeCounter.setText("");
//receive the inputted values
FoodIncome = Integer.parseInt(FoodIncomeCounter.getText().toString());
break;
case R.id.FoodCampSubmitButton:
//reset to value
FoodCamp1Counter.setText("");
FoodCamp2Counter.setText("");
FoodCamp3Counter.setText("");
FoodUpgrade1Counter.setText("");
FoodUpgrade2Counter.setText("");
FoodUpgrade3Counter.setText("");
//receive the inputted values
FoodCamp1 = Integer.parseInt(FoodCamp1Counter.getText().toString());
FoodCamp2 = Integer.parseInt(FoodCamp2Counter.getText().toString());
FoodCamp3 = Integer.parseInt(FoodCamp3Counter.getText().toString());
FoodUpgrade1 = Integer.parseInt(FoodUpgrade1Counter.getText().toString());
FoodUpgrade2 = Integer.parseInt(FoodUpgrade2Counter.getText().toString());
FoodUpgrade3 = Integer.parseInt(FoodUpgrade3Counter.getText().toString());
//get food income and show
TotalFood = FoodCamp1 + (FoodCamp2 * 2) + (FoodCamp3 * 3) + (FoodUpgrade1 * 2) + (FoodUpgrade2 * 4) + (FoodUpgrade3 * 6);
//These 3 options are what iv tried and do not work
FoodIncomeCounter.setText(TotalFood.getText().toString());
FoodIncomeCounter = Integer.parseInt(TotalFood.getText());
String FoodIncomeCounter = String.valueOf(TotalFood);
//------------------------------------------------------
break;
default:
break;
}
}
Change
FoodIncomeCounter.setText(TotalFood.getText().toString());
to
FoodIncomeCounter.setText(String.valueOf(TotalFood));
As getText() is a method on components like EditText, TextView, and not datatypes.
Based on some educated guesses on the types of your fields, the following should work, as TotalFood is probably a number:
FoodIncomeCounter.setText(String.valueOf(TotalFood));
getText() is a method on EditTexts but it doesn't work on numbers.

Extracting data from multiple EditTexts without code repetition

I'd like to efficiently extract data from the EditText fields in a form, without having to repeat the same code multiple times. Here's my current implementation for four EditTexts:
EditText editText1 = (EditText) findViewById(R.id.editText1);
String message1 = editText1.getText().toString();
formData.put("data1", message1);
EditText editText2 = (EditText) findViewById(R.id.editText2);
String message2 = editText2.getText().toString();
formData.put("data2", message2);
EditText editText3 = (EditText) findViewById(R.id.editText3);
String message3 = editText3.getText().toString();
formData.put("data3", message3);
EditText editText4 = (EditText) findViewById(R.id.editText4);
String message4 = editText4.getText().toString();
formData.put("data4", message4);
The general ways for not repeating code are usually loops and functions. In this case you should add your EditTexts to an array like data structure and loop over them.
For example:
You could store the edit Texts in a Hash map and then use a loop to add them to the form:
new HashMap<EditText, String>() {{
put(R.id.et1, "name");
put(R.id.et2, "phone");
//etc...
}}.forEach((editText, s) -> formData.put(s, editText.getText().toString()));
If you don't mind using uninformative names you can just use an array:
EditText[] toAdd = new EditText[]{findViewById(R.id.et1), findViewById(R.id.et2)};
for (int i = 0; i < toAdd.length; i++) {
formData.put("data" + i, toAdd[i].getText().toString());
}
Or for a nice mix of both, you can use the ID of the EditText as the name
EditText[] toAdd = new EditText[]{findViewById(R.id.et1), findViewById(R.id.et2)};
for (EditText editText : toAdd) {
formData.put(getResources().getResourceEntryName(editText.getId()), editText.getText().toString());
}

Removing All Views gets rid of OnClickListener

I am adding some table rows to a tableLayout dynamically and adding an onClickListener to each row- but when I removeAllViews, for some reason it gets rid of the listener too....
Here is my code for adding the data:
private void addTickerToTable(String ticker, String last, String chg, String pchg, String time){
rowId++;
int theColor=Color.WHITE;
int rowColor=0;
float theSize=13f;
lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row= new TableRow(this);
row.setPadding(0, 5, 0, 5);
if(rowOdd==0){row.setBackgroundColor(Color.parseColor("#343434"));rowColor=Color.parseColor("#343434");}
if(rowOdd==1){row.setBackgroundColor(Color.BLACK);rowOdd=-1;rowColor=Color.BLACK;}
rowOdd++;
row.setLayoutParams(lp);
tv0 = new TextView(this);
tv0.setTextColor(Color.parseColor("#3A54A7"));
tv0.setTextSize(theSize);
tv1 = new TextView(this);
tv1.setTextColor(theColor);
tv1.setTextSize(theSize);
tv2 = new TextView(this);
tv2.setTextSize(theSize);
tv3 = new TextView(this);
tv3.setTextSize(theSize);
tv0.setText(ticker);
tv0.setLayoutParams(params);
row.addView(tv0);
tv1.setText(last);
tv1.setLayoutParams(params);
row.addView(tv1);
tv2.setText(chg);
tv2.setLayoutParams(params);
row.addView(tv2);
tv3.setText(pchg);
tv3.setLayoutParams(params);
row.addView(tv3);
ll.addView(row,rowCount);
row.setId(rowId);
row.setOnClickListener(this);
row.setOnLongClickListener(this);
row.startAnimation(anim2);
rowCount++;
}
Then I have a separate method that simply resets the data-
ll.removeAllViews();
rowCount=0;
rowOdd=0;
rowId=0;
It runs perfect the first time- everything is clickable etc...but as soon as you refresh or run the reset code, all of a sudden the onClickListeners don't work...
Nevermind- looks like I wasn't resetting my clicked variable- Oops!

Android set edittext values into multiple textviews

I want to set text of edittext into multiple textviews like if i enter 'HELLO', then H will be set to a textview, E to another.
I have written below code where text is showing one by one on Toast message.
App crashes if i use textview.settext();
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s=editText.getText().toString();
char charArray[] = s.toCharArray();
for(int i=0;i<charArray.length;i++){
char r=charArray[i];
Toast.makeText(getApplicationContext(), ""+r, Toast.LENGTH_LONG).show();
}
}
});
i think you should do something like the following :
ArrayList<TextView> tvList = new ArrayList<TextView>();
String str = "hello";
for(int i=0 ;i<tvList.size() ; i++){
tvList.get(i).setText(str.charAt(i)+"");
}
what you should be doing is saving your textviews in a list , then do as i menthoind .
Hope that helps .

Android: IndexOutOfBounds Error when deleting row in ListView

I have an application that has 2 screens. The first screen has a ListView of movies with a row consisting of 3 Elements: Title, Date and Gross declared in strings.xml. The user has the option of adding a movie by clicking the menu button, which sends him to another screen. The second screen has 3 Edit texts that correspond to Title Date and Gross, which is alphabetically sorted straight away when it returns to screen 1.
Similarly, the user can also Edit/Delete entries by long clicking a row thatbrings up a context menu. The Edit function works like this:
a.) User long clicks Titanic and chooses Edit
b.) Row gets deleted, and user is brought to screen 2
c.) Edit texts are populated with the initial data from the deleted Row
d.) When user edits data, new movie is added at the bottom of the ListView.
The problem arises when the user deletes this new movie at the bottom of the ListView. Logcat gives a
java.lang.IndexOutOfBoundsException: Invalid index 50, size is 50
Here is my code (Take note I am using Perst to persist data, but I don;t think that won't really matter with my problem):
case R.id.contextedit:
Lab9_082588FetchDetails row = (Lab9_082588FetchDetails) getListView()
.getItemAtPosition(info.position);
Intent editData = new Intent(MovieList.this, Lab9_082588Edit.class);
String startTitle = row.getTitle();
String startGross = row.getGross();
String startDate = row.getDate();
editData.putExtra(Lab9_082588Edit.TITLE_STRING, startTitle);
editData.putExtra(Lab9_082588Edit.GROSS_STRING, startGross);
editData.putExtra(Lab9_082588Edit.DATE_STRING, startDate);
startActivityForResult(editData, MovieList.EDIT_MOVIE);
int posEdit = info.position;
String editTitle = results.get(info.position).getTitle();
results.remove(posEdit);
adapter.notifyDataSetChanged();
//Perst
Index<Lab9_082588FetchDetails> rootEdit = (Index<Lab9_082588FetchDetails>) db
.getRoot();
rootEdit.remove(editTitle, results.get((int) info.id));
db.setRoot(rootEdit);
return true;
Edit Class:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection using item.getItemId()
switch (item.getItemId()) {
case R.id.edit:
next();
break;
}
return true;
}
private void next() {
// TODO Auto-generated method stub
EditText movieTitle = (EditText) findViewById(R.id.etTitle);
EditText movieGross = (EditText) findViewById(R.id.etGross);
EditText movieDate = (EditText) findViewById(R.id.etDate);
String title = movieTitle.getText().toString();
String gross = movieGross.getText().toString();
String date = movieDate.getText().toString();
if ((title.length() > 0) && (gross.length() > 0)
&& (date.length() == 4)) {
Intent hobby = getIntent();
hobby.putExtra(Lab9_082588Edit.TITLE_STRING, title);
hobby.putExtra(Lab9_082588Edit.GROSS_STRING, gross);
hobby.putExtra(Lab9_082588Edit.DATE_STRING, date);
setResult(RESULT_OK, hobby);
finish();
}
}
Delete function:
int posDelete = info.position;
String deleteTitle = results.get(
info.position).getTitle();
results.remove(posDelete);
adapter.notifyDataSetChanged();
Index<Lab9_082588FetchDetails> rootDelete = (Index<Lab9_082588FetchDetails>) db
.getRoot();
rootDelete.remove(deleteTitle,
results.get(info.position));
db.setRoot(rootDelete); //Perst
return;
OnActivityResult (Edit):
case EDIT_MOVIE:
Lab9_082588FetchDetails edittedMovie = new Lab9_082588FetchDetails();
NumberFormat formatterEdit = new DecimalFormat("###,###,###");
edittedMovie.setTitle(data
.getStringExtra(Lab9_082588Add.TITLE_STRING));
edittedMovie.setGross("$"
+ formatterEdit.format(Double.parseDouble(data
.getStringExtra(Lab9_082588Add.GROSS_STRING))));
edittedMovie.setDate(data
.getStringExtra(Lab9_082588Add.DATE_STRING));
results.add(edittedMovie);
adapter.notifyDataSetChanged();
Populating the Listview:
for (int i = 0; i < items.size(); i++) {
Lab9_082588FetchDetails sr = new Lab9_082588FetchDetails();
sr.setTitle(items.get(i).getTitle());
sr.setGross(items.get(i).getGross());
sr.setDate(items.get(i).getDate());
results.add(sr);
Collections.sort(results, ignoreCaseStart);
}
How do I remedy this?
This problem occurs because in your delete function, you first remove the element from the results collection("results.remove(posDelete);"), and then, a few lines later, you call "results.get(info.position)" to fetch a parameter for the rootDelete.remove call, but which is already removed.
If the element is the last element of your collection, let's say the 50th element, the value for "info.position" is 50. You remove one element, so the number of elements is now 49. In the rootDelete.remove line you call results.get(50), which produces the error.

Categories

Resources