I'm trying to transfer two numerical inputs from one activity to another's UI but when I click the button to change intent it crashes.
I get the following in logcat: http://pastebin.com/zkWPcSNZ , which suggests a problem with the way I parsed the data to the editTexts in CalcResult.
My question is what is wrong with the way I'm trying to pass the data to the CalcResult editText.Is there an alternative method of acheiving this?
My two classes look like this for reference:
public class MainActivity extends Activity implements OnClickListener {
//variables for xml objects
EditText offsetLength,offsetDepth,ductDepth;
Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting the variables to the xml id's and setting the click listener on the calc button
offsetLength = (EditText)findViewById(R.id.offLength);
offsetDepth = (EditText)findViewById(R.id.offDepth);
ductDepth = (EditText)findViewById(R.id.ductDepth);
calculate = (Button)findViewById(R.id.calc);
calculate.setOnClickListener(this);//don't cast the listener to OnClickListener
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
String getoffsetlength = offsetLength.getText().toString();
String getoffsetdepth = offsetDepth.getText().toString();
String getductdepth = ductDepth.getText().toString();
double tri1,tri2;
double marking1,marking2;
double off1 = Double.parseDouble(getoffsetlength);
double off2 = Double.parseDouble(getoffsetdepth);
double off3 = Double.parseDouble(getductdepth)
;
marking1 = Math.pow(off1,2) + Math.pow(off2,2);
tri1 = (float)off2/(float)off1;
tri2 = (float)off3/Math.atan((float)tri1);
marking2 = (float)off3/Math.atan(tri2);
Intent myIntent = new Intent(MainActivity.this, CalcResult.class);
myIntent.putExtra("numbers", marking1);
myIntent.putExtra("numbers", marking2);
startActivity(myIntent);
} catch (NumberFormatException e) {
// TODO: handle exception
System.out.println("Must enter a numeric value!");
}
}
}
This is the activity that I'm passing the data to:
public class CalcResult extends MainActivity
{
EditText result1,result2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
result1 = (EditText)findViewById(R.id.mark1);
result2 = (EditText)findViewById(R.id.mark2);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
double mark1 = bundle.getDouble("number1");
double mark2 = bundle.getDouble("number2");
int a = Integer.valueOf(result1.getText().toString());
int b = Integer.valueOf(result2.getText().toString());
result1.setText(a + " ");
result2.setText(b + " ");
}
}
When you start your second activity, both editText are empty
So when you do :
int a = Integer.valueOf(result1.getText().toString());
int b = Integer.valueOf(result2.getText().toString());
it's equivalent to :
int a = Integer.valueOf("");
int b = Integer.valueOf("");
which throws the exception
Caused by: java.lang.NumberFormatException: Invalid int: ""
If you want to set them the values you passed through both activities, you can just do :
double mark1 = bundle.getDouble("number1");
double mark2 = bundle.getDouble("number2");
result1.setText(mark1 + " ");
result2.setText(mark2 + " ");
The error is that you are putting your extras with same key "numbers" , and you are trying to retreive them by another keys "number1" and "number2". your code should be like this :
Intent myIntent = new Intent(MainActivity.this, CalcResult.class);
myIntent.putExtra("number1", marking1);
myIntent.putExtra("number2", marking2);
and to retreive them you should use :
Intent intent = getIntent();
double mark1 = intent.getDoubleExtra("number1", 0);
double mark2 = intent.getDoubleExtra("number2", 0);
And then , set the variables on your EditTexts like this :
result1 = (EditText)findViewById(R.id.mark1);
result2 = (EditText)findViewById(R.id.mark2);
result1.setText(mark1+"");
result2.setText(mark2+"");
you are using the same name for your extras when sending the intent, try correcting them.
Related
This is my first project in Android studio. code is a little messy. Im creating a score keeping app for a card game I play with family members.
Im having a problem adding score to main activity from bid activity. how would you store the textview to continue to add to?
Score_activity java code:
public class score_activity extends AppCompatActivity {
// creating an object of the text view
TextView scoreA;
TextView scoreB;
TextView tvA;
TextView tvB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
// assigning the outputs of the user to the object
scoreA = (TextView) findViewById(R.id.scoreA);
scoreB = (TextView) findViewById(R.id.scoreB);
tvA = (TextView) findViewById(R.id.nameA);
tvB = (TextView) findViewById(R.id.nameB);
Bundle bundle = getIntent().getExtras();
String text1 = bundle.getString("Team A");
String text2 = bundle.getString("Team B");
String text3 = getIntent().getStringExtra("ScoreA");
String text4 = getIntent().getStringExtra("ScoreB");
// setting the fetched data to the corresponding text views
tvA.setText(text1);
tvB.setText(text2);
scoreA.setText(text3);
scoreB.setText(text4);
// this method is the logic that increases the value in the text
view by one on every click for team A
}
Bid Activity code
public void scoreTotal(View view) {
String nameA = tvTeamA.getText().toString();
String nameB = tvTeamB.getText().toString();
int bida = Integer.parseInt(bidA.getText().toString());
int tricksTotalA =
Integer.parseInt(tricksA.getText().toString());
int totalB = 25 - tricksTotalA;
int totalScoreBA = mentionteamA + tricksTotalA;
int totalScoreBB = mentionteamB + totalB;
if (bida > totalScoreBA) {
scoreA2 = (bida * -1);
String scoreBoardA = String.valueOf(scoreA2);
String scoreBoardB = String.valueOf(totalScoreBB);
Intent i = new Intent(bid_activity.this,
score_activity.class);
i.putExtra("Team A", nameA);
i.putExtra("Team B", nameB);
i.putExtra("ScoreA", scoreBoardA);
i.putExtra("ScoreB", scoreBoardB);
// starting the activity
startActivity(i);
}
if (bida <= totalScoreBA) {
scoreA2 = totalScoreBA;
String scoreBoardA = String.valueOf(scoreA2);
String scoreBoardB = String.valueOf(totalScoreBB);
Intent i = new Intent(bid_activity.this,
score_activity.class);
i.putExtra("Team A", nameA);
i.putExtra("Team B", nameB);
i.putExtra("ScoreA", scoreBoardA);
i.putExtra("ScoreB", scoreBoardB);
// starting the activity
startActivity(i);
}
if (tricksTotalA == 25) {
scoreA2 = totalScoreBA;
int displayB = 0;
String scoreBoardA = String.valueOf(scoreA2);
String scoreBoardB = String.valueOf(displayB);
Intent i = new Intent(bid_activity.this,
score_activity.class);
i.putExtra("Team A", nameA);
i.putExtra("Team B", nameB);
i.putExtra("ScoreA", scoreBoardA);
i.putExtra("ScoreB", scoreBoardB);
// starting the activity
startActivity(i);
}
One idea is to call
startActivityForResult(i)
instead of
startActivity(i)
Then you can pass a result in BidActivity and capture it in ScoreActiivty's onActivityResult call.
I am just showing how to pass data from your bid activity to score activity.
bid activity
Intent i = new Intent(bid_activity.this, score_activity.class);
i.putExtra("ScoreA2", scoreA2);
i.putExtra("ScoreB2", scoreB2);
startActivity(intent);
score activity
int scoreA2 = getIntent().getIntExtra("ScoreA2");
int scoreB2 = getIntent().getIntExtra("scoreB2");
And for double click, you can follow this thread.
i declare int score = 100 in my 1st activity and use it to my 2nd activity, now the int score is declared as array in 2nd act. but its declared in local variable so how can i use it to my 3rd activity?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level2);
ans1 = findViewById(R.id.ans1);
btn1 = findViewById(R.id.btn1);
Intent i = getIntent();
final int[] score2 = {i.getIntExtra("fscore", 0)};
scr1 = (TextView) findViewById(R.id.scr1);
scr1.setText(String.valueOf(score2[0]));
btn1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
String answer = ans1.getText().toString();
if (score2[0] == 0)
{
Toast.makeText(getApplication(),"You Lose!", Toast.LENGTH_SHORT).show();
gameover();
}
else
{
if (answer.equalsIgnoreCase("ANSWER2"))
{
Toast.makeText(getApplication(),"CORRECT!!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplication(),"Wrong Answer -10 Points", Toast.LENGTH_SHORT).show();
score2[0] = score2[0] - 10;
scr1.setText(String.valueOf(score2[0]));
}
}
}
});
}
public void gameover()
{
Intent intent = new Intent(this, gameover.class);
startActivity(intent);
}
}
If you want to pass score on game over then your funtion body should look like :
Intent intent = new Intent(this, gameover.class).putExtra("score",yourIntValue);
startActivity(intent);
In your second activity :
intent.getIntExtra("score", defValue); // store in a variable or add in an array
it will give you that int value you passed and you can either add it in your array or pass it to third activity using same method as above.
One thing I noticed that you got an int array because you tried making that variable final to use in inner functions right?
final int[] score2 = {i.getIntExtra("fscore", 0)};
Why don't you go for declaring a global scope variable with private access if you are using the same value multiple times.
private int score2;
assign it a value where you have written final int[ ] score2 = {i.getIntExtra("fscore", 0)};,
score2 = i.getIntExtra("fscore",0);
now use score2 wherever you want.There won't be a need of taking array here
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 get the data from the first Activity. In the second Activity, I try to input a value, so that
y = beta0 + beta1 * x. But when I input x, the result y is 0.
This is my code:
public class PredictValue extends Activity implements OnClickListener {
private EditText et_x;
Button btnPredict;
TextView RegressionModel, ResultY;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.predict_value);
Intent i = getIntent();
Bundle bundle = i.getExtras();
String beta1 = bundle.getString("beta1");
String beta0 = bundle.getString("beta0");
et_x = (EditText)findViewById(R.id.et_preX);
btnPredict = (Button)findViewById(R.id.btn_predict);
RegressionModel = (TextView)findViewById(R.id.tv_model);
ResultY = (TextView)findViewById(R.id.tv_predict_y);
RegressionModel.setText("y = " + beta0 + "+" + beta1 + "x");
btnPredict.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editable editableValue_x = et_x.getText();
float value_x = 0,
result_y,
beta1,
beta0;
Intent i = getIntent();
Bundle bundle = i.getExtras();
beta1 = bundle.getFloat("beta1");
beta0 = bundle.getFloat("beta0");
if (editableValue_x != null)
value_x = Float.parseFloat(editableValue_x.toString());
result_y = beta0 + (beta1 * value_x);
//the calculation do here//
ResultY.setText("y =" + result_y);
}
}
This is part of Activity 1. I try to use this code to pass the data to activity2.
public void next (View nxt){
Intent i = new Intent (this, PredictValue.class);
Bundle extras = new Bundle();
extras.putString("beta1", ResultBeta1.getText().toString());
extras.putString("beta0", ResultBeta0.getText().toString());
i.putExtras(extras);
startActivity(i);
}
As I suspected you're putting strings into the first activity's bundle
extras.putString("beta1", ResultBeta1.getText().toString());
extras.putString("beta0", ResultBeta0.getText().toString());
And you are trying to extract floats
beta1 = bundle.getFloat("beta1");
beta0 = bundle.getFloat("beta0");
which, as expected, are 0.
Extract the values from the bundle in the same form as you put them in. So in this case you need to change it to:
beta1 = Float.parseFloat(bundle.getString("beta1"));
beta0 = Float.parseFloat(bundle.getString("beta0"));