I'm working on my first project in Android Studio and I got stuck in "how to display different variables in one textView". to be more clear I'm working on an app that requires the user to enter the gender. each gender has its own calculation method. so I want to display the result calculation the user do in the main interface and In one TextView. I've tried many times to do it but the result is "0.0"
I added another textView and assigned each calculation method to one textview I was able to display the two results.
public class Main_Interface extends AppCompatActivity implements View.OnClickListener{
private TextView results;
//private TextView fResults;//this is the second textview that I created.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__interface);
results = (TextView)findViewById(R.id.results);
if(results.getText().toString().equals("0.0")) {
results.setVisibility(View.INVISIBLE);
}
//fResults = (TextView)findViewById(R.id.fResults);
// if(fResults.getText().toString().equals("0.0")){
// fResults.setVisibility(View.INVISIBLE );
// }
calculateMale();
calculateFemale();
}
public void calculateMale(){
SharedPreferences s = getSharedPreferences("data", Context.MODE_PRIVATE);
double weight = s.getFloat("weight",0.0f);
double height = s.getFloat("height",0.0f);
int age = s.getInt("theDate", 0);
double results2 = 66+(13.7*weight)+(5*height)-(6.8*age);
results.setText(""+results2);
public void calculateFemale(){
SharedPreferences s1 = getSharedPreferences("data", Context.MODE_PRIVATE);
double fWeight = s1.getFloat("fWeight",0.0f);
double fHeight = s1.getFloat("fHeight",0.0f);
int Fage = s1.getInt("theDate", 0);
double results3 = 655 + (9.6 * fWeight) + (1.8 * fHeight) - (4.7 *Fage)
;
fResults.setText(""+results3);
SharedPreferences.Editor editor = s1.edit();
editor.putFloat("results", (float) results3);
editor.commit();
}
}
displaying the calculation in one textview.
You Are calling these two methods before checking these two methods
calculateMale();
calculateFemale();
in onCreate() {
//do this
calculateMale();
calculateFemale();
//Then check the result to make results visible or invisible.
results = (TextView)findViewById(R.id.results);
if(results.getText().toString().equals("0.0")) {
results.setVisibility(View.INVISIBLE);
}
}
You just need to make it clear when the function is being called. What actually happening here is you are checking textView's value even before calculating your required values. So it is throwing 0.0.
Simply call calculateMale(); calculateFemale(); before checking textView's value.
You are printing results before calling the two function. Try this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__interface);
results = (TextView)findViewById(R.id.results);
calculateMale();
calculateFemale();
if(results.getText().toString().equals("0.0")) {
results.setVisibility(View.INVISIBLE);
}
}
Return the result from calculateMale() and calculateFemale() methods:
String calculateMale = calculateMale();
String calculateFemale = calculateFemale();
results = (TextView)findViewById(R.id.results);
String result = calculateMale.concat(calculateFemale);
if (result.length() >= 0) {
results.setText(result);
} else {
results.setVisibility(View.INVISIBLE);
}
Related
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 6 years ago.
In the program below used for an android app in android studios, When getPercent() from the second class(Main2Activity) is invoked, it always returns 999(the default value), and the,
ttper = .....;
statement from the main class in the onClick() is never executed. Is there any specific reason for this? Can you guys point it out please!
This is the main activity,
public class MainActivity extends AppCompatActivity {
float i1m,i2m,mm,atp,assp;
float ttper=999;
boolean b=false;
EditText i1,i2,model,assignment,attendence;
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Context cont = this;
final Intent intent = new Intent(cont, Main2Activity.class);
b1=(Button)findViewById(R.id.button2);
b1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//try {
i1=(EditText)findViewById(R.id.int1);
i2=(EditText)findViewById(R.id.int2);
model=(EditText)findViewById(R.id.mod);
assignment=(EditText)findViewById(R.id.assign);
attendence=(EditText)findViewById(R.id.attend);
i1m = Float.parseFloat(String.valueOf(i1.getText()));
i2m = Float.parseFloat(i2.getText().toString());
mm = Float.parseFloat(model.getText().toString());
assp = Float.parseFloat(assignment.getText().toString());
atp = Float.parseFloat(attendence.getText().toString());
ttper = ((i1m / 10) + (i2m / 10) + ((mm / 100) * 15) + (assp) + ((atp >= 75.0f) ? ((atp - 75) / 5) : 0.0f));
//setValues();
startActivity(intent);
//}
//catch (Exception e) {
// Log.e("app crash",e.getMessage());
//}
}
});
}
/*void setValues()
{
/* i1m = Float.parseFloat(String.valueOf(i1.getText()));
i2m = Float.parseFloat(i2.getText().toString());
mm = Float.parseFloat(model.getText().toString());
assp = Float.parseFloat(assignment.getText().toString());
atp = Float.parseFloat(attendence.getText().toString());*/
}/*
float getPercent()
{
//float ttper=50.0f;
return ttper;
}
}
This is the second activity,
public class Main2Activity extends AppCompatActivity {
float tper=1.0f;
String str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView v1 = (TextView) findViewById(R.id.textView11);
MainActivity m1 = new MainActivity();
//m1.setValues();
//try {
str = String.valueOf(m1.getPercent()) + "%";
v1.setText(str);
//}
//catch (Exception e) {
// Log.e("app crash",e.getMessage());
//}
}
}
it can not work. If you create new MainActivity(), your ttper will be 999.
You should pass data between Activities in this way:
Put the new calculated ttper into Intent: intent.putExtra("ttper", ttper );
Then in MainActivity2 use getIntent().getFloatExtra("ttper", 999.0f);
You have an instance of MainActivity which has a variable ttper. You modify that value.
Then in another class Main2Activity you create a NEW instance of MainActivity and try to get that value, but ttper has the default value because this is a NEW instance and it hasn't been modified yet.
What you can do is defining ttper as static:
static float ttper=999;
You can even define your function getPercent() as static so you don't have to create a new instance of this class to get the value. You would just call MainActivity.getPercent().
For more information, read:
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Anyway, this is not the correct way of passing data from one activity to another. You should follow this guidelines: https://developer.android.com/training/basics/firstapp/starting-activity.html
You should use extras on intents to pass data between activies.
This question already has an answer here:
How to receive an int through an Intent
(1 answer)
Closed 4 years ago.
I'm trying to pass an Integer (from an edittext) to another activity through an intent.
When the user clicks a button, the text in the edittext will transform into a string and then into an int, then the int will be sent through an intent to another activity, but i have to use the int after that.
Here the activity sending the intent:
public class HomeActivityPro extends ActionBarActivity {
private InterstitialAd interstitial;
EditText conttext = (EditText) findViewById ( R.id.texthome );
Button buttone = (Button) findViewById(R.id.buttone);
String maxom = conttext.getText().toString();
int maxam = Integer.parseInt(maxom);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
View.OnClickListener maxim = new View.OnClickListener() {
#Override
public void onClick (View view) {
Intent wall = new Intent(HomeActivityPro.this, GuessOne.class);
wall.putExtra("maxPressed", maxam);
startActivity(wall);
}
};
buttone.setOnClickListener(maxim);
Here the activity receiving it:
public class GuessOne extends ActionBarActivity {
int randone;
int contone;
int wall = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_guess_one);
wall = getIntent().getIntExtra("maxPressed", -1);
randone = (int) (Math.random()*10+1);
contone = 0;
}
Here i'm using it:
public void guessone (View view){
contone++;
textcontone.setText(getString(R.string.attempts) + "" + contone);
if (contone >= wall ){
resultaone.setText("You Failed" + " " + wall);
Toast.makeText(this, "You Failed", Toast.LENGTH_LONG).show();
}
When i use the app, the value of the int is always -1. Where i am wrong.
You can't use findViewById without setting the xml to the activity. That means you need to use findViewById method only after you have called setContentView.
Also you need to read the EditText text value once you click on the button otherwise it always will be null/empty.
Do this
public class HomeActivityPro extends ActionBarActivity {
private InterstitialAd interstitial;
EditText conttext;
Button buttone;
String maxom;
int maxam = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
conttext = (EditText) findViewById ( R.id.texthome );
buttone = (Button) findViewById(R.id.buttone);
View.OnClickListener maxim = new View.OnClickListener() {
#Override
public void onClick (View view) {
maxom = conttext.getText().toString();
maxam = Integer.parseInt(maxom);
Intent wall = new Intent(HomeActivityPro.this, GuessOne.class);
wall.putExtra("maxPressed", maxam);
startActivity(wall);
}
};
buttone.setOnClickListener(maxim);
Problem 1
Put this in the on click listener instead:
String maxom = conttext.getText().toString();
int maxam = Integer.parseInt(maxom);
You want the values to be read at the time you click the button not when you open the activity, correct?
Problem 2
The following needs to be after setContentView in onCreate:
conttext = (EditText) findViewById ( R.id.texthome );
buttone = (Button) findViewById(R.id.buttone);
Keep the declarations where they are. Just the declarations:
EditText conttext;
Button buttone;
Note
Follow the same pattern in all your activities. Declare views as field variables, assign them in onCreate after setContentLayout. Get the values at the time they're needed.
public int getIntExtra (String name, int defaultValue)
Added in API level 1 Retrieve extended data from the intent.
Parameters name The name of the desired item. defaultValue the value
to be returned if no value of the desired type is stored with the
given name. Returns the value of an item that previously added with
putExtra() or the default value if none was found. See Also
putExtra(String, int)
This means that no int was found when you called getIntExtra(valueName, defaultValue); so the default value was chosen.
You should check to see what your maxam value is before you call the new activity.
In the activity you receive it:
wall = getIntent().getIntExtra("maxPressed");
SOLVED: by getInt and String.valueOf
private static final String IMGID = "ImgID";
if (getIntent().getExtras().containsKey(IMGID)) {
//Picasso.with(this).load(getIntent().getExtras().getString(IMG)).into(mImg);
Picasso.with(this).load(getIntent().getExtras().getInt(String.valueOf(IMGID))).into(mImg);
}
I'm struggling to figure out why I can't pass an int value from one activity to another. The app will ask you to press a button to generate a random number from 1-100 which will be displayed below the button. There is also another button which will open a new activity simply showing the random number that was rolled... but I just get 0.
I've looked into similar questions asked but to no avail.
Here's my code from MainActivity
public class MainActivity extends ActionBarActivity {
int n;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ButtonRoll(View view) {
TextView textRoll = (TextView) findViewById(R.id.textview_roll);
Random rand = new Random();
n = rand.nextInt(100) + 1;
String roll = String.valueOf(n);
textRoll.setText("Random number is " + roll);
}
public void OpenStats(View view) {
Intent getStats = new Intent(this, Stats.class);
startActivity(getStats);
}
public int GetNumber (){ return n; }
}
Heres my 2nd class.
public class Stats extends Activity {
MainActivity statistics = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
int n = statistics.GetNumber();
TextView tvStats = (TextView) findViewById(R.id.passedNumber_textview);
String number = String.valueOf(n);
tvStats.setText(number);
}
}
Is using getters the wrong way to get data from another class when using activities? Thanks for your time.
You should pass your data as an extra attached to your intent. To do this you need to first determine a global key to be used. You could do something like this in your MainActivity
public static final String SOME_KEY = "some_key";
then modify your OpenStats method to
public void OpenStats(View view) {
Intent getStats = new Intent(this, Stats.class);
getStats.putExtra(SOME_KEY, n);
startActivity(getStats);
}
and then in Stats.class onCreate method
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
int n = getIntent().getIntExtra(MainActivity.SOME_KEY, -1);
TextView tvStats = (TextView) findViewById(R.id.passedNumber_textview);
String number = String.valueOf(n);
tvStats.setText(number);
}
You obviously should make sure that you are calling ButtonRoll at least once or that you set n so that you aren't passing a null int.
Also, as note, convention states that methods should use lower camel case formatting. That is, the first word is completely lower case and the first letter of subsequent words is upper case. That would change your methods
OpenStats() -> openStats()
ButtonRoll() -> buttonRoll()
Classes/objects are upper camel case, just to help avoid confusion.
I have this code :
private ImageView d1;
private ArrayList<Integer> listaImagenes = new ArrayList<Integer>();
private ArrayList<String> listaFrases = new ArrayList<String>();
private Button button;
private Integer contador = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.rellenarImagenes();
setContentView(R.layout.imagentonas);
d1 = (ImageView) findViewById(R.id.imagenes01);
while (contador < listaImagenes.size()) {
d1.setImageResource(listaImagenes.get(contador));
button = (Button) findViewById(R.id.botoncillo);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
contador++;
}
});
}
}
private void rellenarImagenes() {
listaImagenes.add(R.drawable.a01);
listaImagenes.add(R.drawable.a02);
listaImagenes.add(R.drawable.a03)
}
I am trying do a loop that when I press the button , increment contador and d1 change image.
but it is not working, application background remains black and not working.
remove while loop and setimage in onclick method.
You are expecting that modifying the value of the variable contador would result in the array item to change.
Keep in mind that in the code line d1.setImageResource(listaImagenes.get(contador));, the get function receives an int. So at the time where it's called it receives a value, not a reference to an Integer. When you change the value of contador, the value that was used to obtain the index in the array is not changed.
And even if the value did change, d1 would still be using the same resource.
What you need to do in the onClickListener is add the code to set the image. Something along the lines of
public void onClick(View v) {
++contador;
if (contador >= listaImagenes.size())
{
contador=0;
}
//you'll probably need to modify the next line to be able to access the button variable.
//one way to do it is to use a final variable in the onCreate method that creates this OnClickListener
button.setImageResource(listaImagenes.get(contador));
}
The while loop is not needed. What your code is doing is setting the image to the 3 items of the array, one after the other, and adding a new click listener 3 times.
I will try to answer and point some of the flaws you have in the code.
wat if there were 100 drawable like R01 ,R02...? Instead you can use getting drawable using string.
why are you using while loop ? since you have the counter you can directly use that.
Let me try to write the code
int contador=1;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.imagentonas);
context=this;
d1=(ImageView)findViewById(R.id.imagenes01);
button=(Button)findViewById(R.id.botoncillo);
button=(Button)findViewById(R.id.botoncillo);
button.setOnClickListener( new View . OnClickListener () {
public void onClick ( View v ) {
int id = context.getResources().getIdentifier("a"+contador,
"drawable", context.getPackageName());
d1.setImageResource(id);
contador++;
}
});
}
Notice : int id = context.getResources().getIdentifier("a"+contador,"drawable", context.getPackageName()); Here using the string you can access the drawable this solves the issue for any number of consecutive drawables.
Hope you get the concept...
Thanks
I know this is a simpleton question, but I am not going to school for java, just learning it online.
how to a have a textview with an initial value of 0. and then everytime you press a button it ads 25 points to the score board.
At first I wanted the button press to add a random number between 42-57 to the score board.
And then how to do convert that int or long to a string to make it fit into a textview and keep the current score, and then add a new score.
EDIT: ok so someone said I should post the code so here it is.. where do i put this..
TextView txv182 = (TextView) findViewById(R.id.welcome);
txv182.setText(toString(finalScore));
Because when I do it, I get an error: The method toString() in the type Object is not applicable for the arguments (int)
public class MainActivity extends Activity {
// Create the Chartboost object
private Chartboost cb;
MediaPlayer mp = new MediaPlayer();
SoundPool sp;
int counter;
int db1 = 0;
Button bdub1;
TextView txv182;
int finalScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txv182 = (TextView) findViewById(R.id.welcome);
finalScore = 100;
sp = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
db1 = sp.load(this, R.raw.snd1, 1);
bdub1 = (Button) findViewById(R.id.b4DUB1);
bdub1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (db1 != 0)
sp.play(db1, 1, 1, 0, 0, 1);
txv182.setText(finalScore);
}
});
First you need to store your score to certain integer variable say score and set it to any initial value you want and use.
TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setText(toString(score));
you do not need to initialize the textview with value just in onclick() of button do score+=25and add text to your textview as above.
hope this helps
It's actually like this..
pernts+=25;
txv182.setText(String.valueOf(pernts));
in android, after the
public class MainActivity extends Activity {
but before..
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i wrote..
int pernts;
String strI;
so then after the above #Override majigy, i wrote..
strI = "" + pernts;
pernts = 0;
because when i wrote it like.. int pernts = 0; it never worked, forcing me to add final and what not..
any way.. How to convert an integer value to string? anSwered the question..
and so the end was like this
pernts+=25;
txv182.setText(String.valueOf(pernts));
i figured out you have to add a value to the int variable not the string.. i kept wanting to add 25 and i was getting 25252525252525.., instead of 25 50 75 100.. kinda cool actually.. separating the logic of how to "add" 25 .. anyway thanks.. SOF!
30 minutes later... found this.. How can I generate random number in specific range in Android?
..
import android.app.Activity;
public class InsMenu extends Activity {
static TextView txv182;
static int pernts;
Button bdub1;
public static void addPernts() {
int min = 37;
int max = 77;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
pernts+=i1;
txv182.setText(String.valueOf(pernts));
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.BLAHBLAH);
bdub1 = (Button) findViewById(R.id.b4DUB1);
txv182 = (TextView) findViewById(R.id.welcome);
bdub1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
addPernts();
}
--- i created my first objekt thanks to this too.. http://www.tutorialspoint.com/java/java_methods.htm ..