adding values put in by users - android

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));
}
});

Related

TextView set multiple string into a setText(int resid)

Good morning,
How can I put multiple string ressources inside the setText to display them in order ?
I have a layout with a TextView (id: TxtDisp) and a Button (id: NextSentence) that change the text when I click on it.
NextSentence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TxtDisp.setText(R.string.sentence_2);
}
});
Where or how can I put four to six string ressources to be display in order when the button is clicked ?
Thanks in advance !
You could put the string resources in an array, and get the string from that. So add a class member to track the which sentence is next
private int nextSentenceId = 0;
then in onCreate use code like this
final int[] sentences = new int[]{R.string.sentence_1, R.string.sentence_2, R.string.sentence_3};
NextSentence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( nextSentenceId < sentences.length ) {
TxtDisp.setText(sentences[nextSentenceId]);
++nextSentenceId;
}
}
});
Make sure to catch when you are at the last sentence or you will get an array out of bounds error.
You can do it easily when you hold these strings in an array or something and have a counter that hold which string is displayed right now like so
in onCreate() method put your sentences in an ArrayList
ArrayList<Integer> strings = new ArrayList();
strings.add(R.string.sentence1);
strings.add(R.string.sentence2);
strings.add(R.string.sentence3);
then on the button click you can use the counter and track which is selected
NextSentence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TxtDisp.setText(strings.get(count++));
}
});
I hope this would help you

Passing a value via Button ( maybe hidden)

This code was working until last night, but now now. I'm wanting a value to be record that is linked to the buttons, I have used set and get tag but is only returning last value.
//create a layout
LinearLayout layout = (LinearLayout)findViewById(R.id.linearlayout);
// create a list of buttons
for(x=0; x<3; x++)
{
newBut = new Button(this);
newBut.setText("("TEXT");
newBut.setTextColor(Color.parseColor("#FFFFFF"));
newBut.setTag(x); //hide job id within the button.
newBut.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int newValue = Integer.parseInt(newBut.getTag().toString());
System.out.println(newValue); //this just a test to display the value
}
});
layout.addView(newBut);
}
Is the error obvious - not to me.
It is returning the last value, because in all the created listeners you always reference the same button (last value of newBut variable), ignoring the actual click source view you have as the argument. Is should be:
newBut.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int newValue = Integer.parseInt(v.getTag().toString());
System.out.println(newValue);
}
});

How to add a value to a Toast, from a Edittext (with button)

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.

how to set value of edittext with same id in different inflated linearlayout views?

I have one main layout with one LinearLayout. In this LinearLayout I inflates multiple xml layouts that contain a form with multiple text fields(3 EditText) in it.
On first attempt I show only one form. There is button for adding more forms. Suppose If user clicks on "Add" button two times then user have three total forms. I successfully get all data of these three forms.
For doing this I am targeting the main layout "LinearLayout" and then counting its child. After counting its child I called child views of Main LinearLayout by its position and then get EditText data and save into a list. Then I moved this list to next page. Everything works fine till then. But if user comes back on previous page, all inflated layouts were gone. So, I count the size of list on resume and set the values what users wrote last time.
The problem is when I set the values of EditText according to its view position. Only last object(of list) value is shown in all inflated layouts. Means when for loop ends it sets last object value in all layouts. This is my method for setting values against a view:
private void addFormDataOnResume(LinearLayout viewForm,Traveller otherTraveller)
{
EditText dateOfBirthEt = (EditText)viewForm.findViewById(R.id.dateOfBirth);
dateOfBirthEt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDatePickerDialog(dateOfBirthEt);
}
});
dateOfBirthEt.setText(otherTraveller.getOtherDateOfBirth());
EditText firstNameET = (EditText)viewForm.findViewById(R.id.firstName);
firstNameET.setText(otherTraveller.getOtherFirstName());
EditText lastNameEt = (EditText)viewForm.findViewById(R.id.lastName);
lastNameEt.setText(otherTraveller.getOtherLastName());
}
My loop code:
int otherTraSize = otherTravellersData.size();
//adultsForms is the main linear layout in which I am adding views
for(k=0; k < otherTraSize; k++)
{
addFormOnResume();//Function for adding form layout
int viewPos = adultsForms.getChildCount();
if(viewPos>0)
{
addFormDataOnResume(adultsForms.getChildAt(viewPos-1), otherTravellersData.get(k));
}
}
My FUnction for adding forms:
private void addFormOnResume()
{
LinearLayout viewForm = (LinearLayout)layoutInflater.inflate(R.layout.other_traveller_form, null );
adultsForms.addView(viewForm);
}
I debug my code, all data of list seems fine. Objects are in proper order with proper values.
Please help me why only last object value is set to all of the inflated forms.
Any help would be really appreciated......Thanks in Advance.
Finally I got the answer of my own question. By default when an activity goes in onPause mode. Android saves the EditText value against an id and when we resume it restore the last saved value of EditText. So, in my case it restoring last form values in all layout forms. The solution of my problem is to set android:saveEnabled="false" on the widget entry on the XML. I added this in all EditText. Android no longer saves my data and onResume I can set value of my form fields whatever I want to, by simply getting childView from specified position even if they have same Id.
Replace your loop code with this:
int otherTraSize = otherTravellersData.size();
//adultsForms is the main linear layout in which I am adding views
for(k=0; k < otherTraSize; k++)
{
addFormOnResume();//Function for adding form layout
}
int viewPos = adultsForms.getChildCount();
if(viewPos>0)
{
for(int x=0; x<viewPos; x++){
Log.d("current value",otherTravellersData.get(x).getOtherFirstName());
addFormDataOnResume(adultsForms.getChildAt(viewPos-1), otherTravellersData.get(x));}
}
Its my working code
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAdd:
view = layoutInflater.inflate(R.layout.fragment_add_materials, null);
parentLinearLayout.addView(view);
arrayList.add(view);
edtMaterialName = (EditText) view.findViewById(R.id.edtinput_material1);
editTextCoast = (EditText) view.findViewById(R.id.editTextCoast1);
edtMaterialName.addTextChangedListener(getMyTextWatcher(edtMaterialName,arrayListMaterials.size()-1 ,"name"));
editTextCoast.addTextChangedListener(getMyTextWatcher(editTextCoast, arrayListMaterials.size()-1, "cost"));
break;
TextWatcher getMyTextWatcher(final EditText edtText, final int listPosition, String nameOrcost){
return new MyTextWatcher(edtText, listPosition, nameOrcost);
}
class MyTextWatcher implements TextWatcher{
int position;
EditText edtText;
String nameOrcost;
MaterialData data;
boolean flag;
int count;
public MyTextWatcher(EditText edtText1, int listPosition, String nameOrcost){
this.position = listPosition;
this.edtText=edtText1;
this.nameOrcost = nameOrcost;
data = arrayListMaterials.get(position);
}
#Override
public void afterTextChanged(Editable sEditable) {
try{
if(this.nameOrcost.equals("name") && edtText.getEditableText().toString().length()>0){
data.setMaterialName(edtText.getEditableText().toString());
}
if(this.nameOrcost.equals("cost") && edtText.getEditableText().toString().trim().length()>0){
String tempCost = edtText.getEditableText().toString().trim();
NumberFormat myFormatter = NumberFormat.getInstance();
Number number = myFormatter.parse(tempCost);
data.setMaterialprice(new BigDecimal(number.toString()).toString());
}
arrayListMaterials.set(position, data);
setTotalPrice(arrayListMaterials);
}catch (Exception e) {
e.printStackTrace();
}
if(this.nameOrcost.equals("cost") && edtText.getEditableText().toString().trim().length()>0){
Utilty.insertCommaIntoNumber(edtText, sEditable.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
try{
if(this.nameOrcost.equals("cost"))
data.setMaterialprice("0");
if(this.nameOrcost.equals("name"))
data.setMaterialName("");
arrayListMaterials.set(position, data);
}catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
}

Android: random and textView

I have just started learning Android and got some misunderstanding. I'm trying to create an application which displays a textView and a button. Every button click generates a new random number which should be displayed in the textView.
But unfortunately my code causes a list of errors. Here it is:
public class FirstAndroidProjectActivity extends Activity {
public OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.display);
Random r = new Random();
int i = r.nextInt(101);
tv.setText(i);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(listener);
}
}
If I just don't use random and use some string except of i
(for example tv.setText("99");) everything is ok, but it doesn't work with a variable as a parameter of setText().
Where is a mistake?
Hope for your help.
You need to convert your random number to a string before setting the text on your TextView
Try
tv.setText(i +"");
Try:
tv.setText(String.valueOf(i));
Java doesn't auto convert types. The + operator is overloaded to transform the parameters passed to it into a String when one or more of those paramaters is a String. So, when you pass i + "" to setText() you are passing a String, however if you just pass i then the compiler sees you passing an int to a method that expects a String and lets you know that that can't be done.
i is an int, try tv.setText("" + i);
Convert your integer to a String before setting it to the textView. You should also move Random r = new Random(); outside of the method, or else your numbers may not really be random :
Random r = new Random();
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.display);
int i = r.nextInt(101);
tv.setText(Integer.toString(i));
}
From the documentation :
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers
If you create two Random objects too quickly (for example the user clicks two times on the button very quickly), they will share the same seed (the system clock is used to generate it) and as a result you will get the same number two times.
By creating only one Random instance in a global variable, you avoid this issue.
use
tv.setText(new Integer(i).toString()) ;

Categories

Resources