Rishi Swethan Rishi Swethan - 2 months ago 6
Java Question

Some of my code is not executing in android studios?

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

}

dit dit
Answer

it can not work. If you create new MainActivity(), your ttper will be 999.

You should pass data between Activities in this way:

  1. Put the new calculated ttper into Intent: intent.putExtra("ttper", ttper );

  2. Then in MainActivity2 use getIntent().getFloatExtra("ttper", 999.0f);