Passing data from one activity to another causes force close - android

I'm new to Android Programming world and this is driving me crazy. Any help would be appreciated !
Everything works fine except the intent putextra , getextra code part. Since when I added this part to the project, whenever I click on a button which would teorically start a new activity, force closes.
Below is MainActivity.java
public class MainActivity extends Activity {
EditText inputA, inputB, inputC;
TextView nrRoots, root1, root2, roots;
Button bStepByStep, calculate;
Double a, b, c, D, x1, x2, x, dRootNr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputA = (EditText) findViewById(R.id.etParamA);
inputB = (EditText) findViewById(R.id.etParamB);
inputC = (EditText) findViewById(R.id.etParamC);
nrRoots = (TextView) findViewById(R.id.tvNrRoots);
root1 = (TextView) findViewById(R.id.tvRoot1);
roots = (TextView) findViewById(R.id.tvRoots);
root2 = (TextView) findViewById(R.id.tvRoot2);
calculate = (Button) findViewById(R.id.bCalculate);
bStepByStep = (Button) findViewById(R.id.bStepByStep);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
a = Double.parseDouble(inputA.getText().toString());
b = Double.parseDouble(inputB.getText().toString());
c = Double.parseDouble(inputC.getText().toString());
double D = Math.sqrt((b * b) - (4 * a * c));
if (D == 0) {
nrRoots.setText("The equation " + a + "x^2+" + b + "x+" + c
+ "=0 has 1 distinct root.");
x = ((-1) * b) / (2 * a);
root1.setText("x=" + x);
root2.setText("");
roots.setText("");
} else if (D > 0) {
nrRoots.setText("The equation " + a + "x^2+" + b + "x+" + c
+ "=0 has 2 distinct roots.");
x1 = (((-1) * b) + D) / (2 * a);
x2 = (((-1) * b) - D) / (2 * a);
root1.setText("x1= " + x1);
root2.setText("x2= " + x2);
} else {
nrRoots.setText("The equation " + a + "x^2+" + b + "x+" + c
+ "=0 has no distinct roots.");
root1.setText("");
root2.setText("");
}
}
});
bStepByStep.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this, NewActivity.class);
i.putExtra("a", a);
i.putExtra("b", b);
i.putExtra("c", c);
i.putExtra("D", D);
i.putExtra("x1", x1);
i.putExtra("x2", x2);
startActivity(i);
finish();
}
});
}
}
here is NewActivity.java
public class NewActivity extends Activity {
Intent i = getIntent();
Double a = i.getExtras().getDouble("a");
Double b = i.getExtras().getDouble("b");
Double c = i.getExtras().getDouble("c");
Double D = i.getExtras().getDouble("D");
Double x1 = i.getExtras().getDouble("x1");
Double x2 = i.getExtras().getDouble("x2");
TextView bb;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.new_activity);
bb = (TextView) findViewById(R.id.tvArbli);
bb.setText("a=" + a + " " + b + " " + c + " " + D + " " + x1 + " " + x2);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
What am I doing wrong ?

You can't retrieve the intent during class instansiation.
Change your code to something like this...
public class NewActivity extends Activity {
Intent i;
TextView bb;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.new_activity);
i = getIntent();
Double a = i.getExtras().getDouble("a");
Double b = i.getExtras().getDouble("b");
Double c = i.getExtras().getDouble("c");
Double D = i.getExtras().getDouble("D");
Double x1 = i.getExtras().getDouble("x1");
Double x2 = i.getExtras().getDouble("x2");
bb = (TextView) findViewById(R.id.tvArbli);
bb.setText("a=" + a + " " + b + " " + c + " " + D + " " + x1 + " " + x2);
}
PS You need to do a lot of validation!
Also, always include you logcat (stack trace) for any sort of crash.

Related

display multiplication table in TextView

I am trying to generate a multiplication table,where the 1st EditText takes the actual number while 2nd EditText takes the actual range of multiplication table. When I run the project , the result is only number * range..
can anyone help me in the loop or code below mentioned Or,any alternatives to display the table in GridLayout or TableLayout rather than TextView.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiplication_table);
number = (EditText)findViewById(R.id.numberTable);
range = (EditText)findViewById(R.id.numberRange);
click = (Button)findViewById(R.id.click);
result = (TextView)findViewById(R.id.display);
final String x = range.getText().toString();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= 10; i++)
{
for(int j = 1 ; j <= 10; j++)
{
int res = a * b;
result. setText(a +" * " + b + " = " + res);
}
}
return;
}
});
}
}
you are calling setText() for every row, but setText() will reset the text of the TextView, you might want to use append() instead
result.setText("");
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= b; i++){
int res = a * i;
result.append(a +" * " + i + " = " + res + "\n");
}
or maybe use StringBuilder
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
StringBuilder builder = new StringBuilder();
for(int i = 1 ; i <= b; i++){
int res = a * i;
builder.append(a +" * " + i + " = " + res + "\n");
}
result.setText(builder.toString())

How to bring forward a integer

This is activityresult1
Button buttonorder;
TextView textviewcard;
private static final int REQUEST_CODE = 10;
int[] image ={R.drawable.friednoodle, R.drawable.friedrice, R.drawable.steamfish,R.drawable.tehice};
String[] item = {"Fried Noodle", "Fried Rice", "Steam Fish","Iced Tea"};
String[] description = {"Classic Chinese stir fried noodle with prawn and Pork", "Special sauce Fried Rice using indian rice", "HongKong Style Steamed Fish ","HongKong classical iced tea"};
String[] cost={"6","5","25","2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activityresult1);
Bundle extras = getIntent().getExtras();
String strcardnumber = extras.getString("Card Number");
textviewcard = (TextView) findViewById(R.id.textviewcard);
textviewcard.setText("Welcome, " + strcardnumber + " !" + "\nPlease select the food you want ! : ");
itemList = new ArrayList<DataInfo>();
itemList.add(new DataInfo(item[0], image[0], description[0], cost[0]));
itemList.add(new DataInfo(item[1], image[1], description[1], cost[1]));
itemList.add(new DataInfo(item[2], image[2], description[2], cost[2]));
itemList.add(new DataInfo(item[3], image[3], description[3], cost[3]));
final MenuAdapter adapter = new MenuAdapter(this);
ListView listView = (ListView)findViewById(R.id.list);
LVAdapter lvAdapter = new LVAdapter(this, itemList);
//listView.setAdapter(lvAdapter);
listView.setAdapter(adapter);
for (int i = 0; i < item.length; i++) {
adapter.addData(String.valueOf(i), item[i], image[i], description[i], cost[i]);
}
buttonorder = (Button) findViewById(R.id.suborder);
buttonorder.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String[] a = adapter.getQuantity();
Toast.makeText(getApplicationContext(), "Noodle: " + a[0] + "\nRice: " + a[1] + "\nSteam fish: " + a[2] + "\nIced tea: " + a[3], Toast.LENGTH_LONG).show();
int sum = Integer.parseInt(adapter.getQuantity()[0])*Integer.parseInt(cost[0]) +
Integer.parseInt(adapter.getQuantity()[1])*Integer.parseInt(cost[1]) +
Integer.parseInt(adapter.getQuantity()[2])*Integer.parseInt(cost[2]) +
Integer.parseInt(adapter.getQuantity()[3])*Integer.parseInt(cost[3]);
Intent myIntent = new Intent(activityresult1.this, activityresult2.class);
myIntent.putExtra("sum",sum);
startActivity(myIntent);
Intent intent = new Intent(getApplicationContext(), activityresult2.class);
Bundle bundle = new Bundle();
bundle.putString("Noodle quantity", adapter.getQuantity()[0]);
bundle.putString("Rice quantity", adapter.getQuantity()[1]);
bundle.putString("Fish quantity", adapter.getQuantity()[2]);
bundle.putString("Iced tea", adapter.getQuantity()[3]);
bundle.putInt("sum", sum);
bundle.putBoolean("ANI", adapter.getItem(0).isAddInisCheck());//add noodle ingredients
bundle.putBoolean("ARI", adapter.getItem(1).isAddInisCheck()); // add rice ingredients
bundle.putBoolean("AFI", adapter.getItem(2).isAddInisCheck());// add fish ingredients
bundle.putBoolean("AIT", adapter.getItem(3).isAddInisCheck()); // add ice tea ingredients
intent.putExtras(bundle);
startActivityForResult(intent, REQUEST_CODE);
}
});
}
how do i sent the calculated sum from activityresult1 to activityresult2
static public String txtOrder ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activityresult2);
Bundle bundle = getIntent().getExtras();
String strfnq = bundle.getString("Noodle quantity");
String strfrq = bundle.getString("Rice quantity");
String strfsq = bundle.getString("Fish quantity");
String stricq = bundle.getString("Iced tea");
Integer strsum = bundle.getInt("sum");
boolean addNingc = bundle.getBoolean("ANI");
boolean addRingc = bundle.getBoolean("ARI");
boolean addFingc = bundle.getBoolean("AFI");
boolean addTingc = bundle.getBoolean("AIT");
// boolean addmoneyc = bundle.getBoolean("AMY");
Intent mIntent = getIntent();
int sum = mIntent.getIntExtra("sum",strsum);
TextView costtext = (TextView)findViewById(R.id.costtext);
costtext.setText(getIntent().getExtras().getString("sum"));
TextView foodorders = (TextView) findViewById(R.id.foodordershow);
foodorders.setText(getIntent().getExtras().getString("Quantity"));
String addNdlThing = "";
if (addNingc) {
addNdlThing = " with addition of ingredients";
}
String addRlThing = "";
if (addRingc) {
addRlThing = " with addition of ingredients";
}
String addSlThing = "";
if ( addFingc) {
addSlThing = " with addition of ingredients";
}
String addTeac = "";
if ( addTingc ) {
addTeac = " with addition of ingredients";
}
foodorders = (TextView) findViewById(R.id.foodordershow);
if(strfnq.equals("") && strfrq.equals("") && strfsq.equals("")&& stricq.equals("")){
txtOrder = "Sorry, You've not ordered any thing , please return to previous menu to order";
}else if (!strfnq.equals("") && !strfrq.equals("") && !strfsq.equals("")&& stricq.equals("")) {
txtOrder = "Thank you , You've ordered\n" + strfnq + " fried noodle" + addNdlThing +" and\n"+ strfrq
+ " fried rice" + addRlThing +" and\n" + strfsq + " Steam fish " + addSlThing + "and\n" + stricq + " Steam fish " + addTeac;
} else {
txtOrder = "Thank you , You've ordered\n";
if(!strfnq.equals("")){
txtOrder = txtOrder + strfnq + " fried noodle" + addNdlThing;
}
if(!strfrq.equals("")){
txtOrder = txtOrder + strfrq + " fried rice" + addRlThing;
}
if(!strfsq.equals("")){
txtOrder = txtOrder + strfsq + " Steam fish" + addSlThing;
}
if(!stricq.equals("")){
txtOrder = txtOrder + stricq + " Iced Tea"+ addTeac;
}
}
foodorders.setText(txtOrder);
}
i want to calculate the money spent in result1 and display it in result 2
i have tried using the method they written at the bottom but it dont work as i dont know what to fill in for some . please help me , i really need help on this , and i am typing alot to make the word count so i can post , as i have too much codes they say , and please stop disliking this post , dont be such persons , like this and it will be happy for both parties , asking question dont mean i am stupid
You can sent the value of the sum to the next activity and get it via Bundle in the other activity like this. Think that your are sending it to the activity B
Intent i= new Intent(this,B.class);
i.putExtra("sum",sum);
startActivity(i);
you can send the context to the activity B through either one of the following this,getActivity(),getApplicationContext()
Then inactivity B you can add these lines in onCreate() method, to get the passed content
Bundle MainActivityData= getIntent().getExtras();
int sum= MainActivityData.getString("sum");

Check Scores in Android Studio

This is my Code. When the user enters their answer and press the Submit Button which is the AnswerCheck Method, i would like the score to be shown in a TextView for example - if they input the right answer, the TextView would state 1 correct out of 1. I would like some help, Thanks
public class Perimeter extends AppCompatActivity {
private int number;
private int number2;
private String myString;
private String myString2;
private int perimeter;
private Random rand;
private Random rand2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perimeter);
rand = new Random();
rand2 = new Random();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void PerimeterGame(View view) {
number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
myString = String.valueOf(number);
myText.setText(myString);
number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
myString2 = String.valueOf(number2);
myText2.setText(myString2);
((TextView) findViewById(R.id.question)).setText
("Find the perimeter of a rectange with a width of " + myString + "cm" + " and " + "length of " + myString2 + "cm" + ".");
}
public void AnswerCheck(View view) {
EditText num = (EditText) findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString());
perimeter = (number + number2 + number + number2);
if (val == perimeter) {
Toast.makeText(this, "The answer is correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "The answer is incorrect ", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.showsolbutton).setEnabled(true);
}
}
Set two global int variables
private int totalQuestion = 0;
and private int correctQuestions = 0;
Inside public void PerimeterGame(View view) increment totalQuestion by one.
When the answer is correct, inside public void AnswerCheck(View view) increment correctQuestion by one.
Finally, display the text
youTextView.setText(String.valueOf(correctQuestions) + " correct out of " + String.valueOf(totalQuestion));
Hope it helps.
public class Perimeter extends AppCompatActivity {
// Code ommitted
private int totalQuestion = 0 ;
private int correctQuestions = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Code ommitted
}
public void PerimeterGame(View view) {
// Increment totalQuestion
totalQuestion++;
number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
myString = String.valueOf(number);
myText.setText(myString);
number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
myString2 = String.valueOf(number2);
myText2.setText(myString2);
((TextView) findViewById(R.id.question)).setText
("Find the perimeter of a rectange with a width of " + myString + "cm" + " and " + "length of " + myString2 + "cm" + ".");
}
public void AnswerCheck(View view) {
EditText num = (EditText) findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString());
perimeter = (number + number2 + number + number2);
if (val == perimeter) {
correctQuestions++;
Toast.makeText(this, "The answer is correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "The answer is incorrect ", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.showsolbutton).setEnabled(true);
// Display text
youTextView.setText(String.valueOf(correctQuestions) + " correct out of " + String.valueOf(totalQuestion));
}
}

Remove decimals from a number shown in a TextView [duplicate]

This question already has answers here:
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 9 years ago.
For my simple calculator, I am showing the result in a TextView, but it is always showing decimals. How can I remove them ?
This is my code :
public class MainActivity extends Activity implements OnClickListener {
EditText etNum1;
EditText etNum2;
Button btnAdd;
Button btnSub;
Button btnMult;
Button btnDiv;
TextView tvResult;
String oper = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find the elements
etNum1 = (EditText) findViewById(R.id.etNum1);
etNum2 = (EditText) findViewById(R.id.etNum2);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnSub = (Button) findViewById(R.id.btnSub);
btnMult = (Button) findViewById(R.id.btnMult);
btnDiv = (Button) findViewById(R.id.btnDiv);
tvResult = (TextView) findViewById(R.id.tvResult);
// set a listener
btnAdd.setOnClickListener((OnClickListener) this);
btnSub.setOnClickListener(this);
btnMult.setOnClickListener(this);
btnDiv.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
double num1=0;
double num2=0;
double result=0;
// check if the fields are empty
if (TextUtils.isEmpty(etNum1.getText().toString())
|| TextUtils.isEmpty(etNum2.getText().toString())) {
return;
}
// read EditText and fill variables with numbers
num1 = Double.parseDouble(etNum1.getText().toString());
num2 = Double.parseDouble(etNum2.getText().toString());
// defines the button that has been clicked and performs the corresponding operation
// write operation into oper, we will use it later for output
switch (v.getId()) {
case R.id.btnAdd:
oper = "+";
result = num1 + num2;
break;
case R.id.btnSub:
oper = "-";
result = num1 - num2;
break;
case R.id.btnMult:
oper = "*";
result = num1 * num2;
break;
case R.id.btnDiv:
oper = "/";
result = num1 / num2;
break;
default:
break;
}
// form the output line
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + result);
}
}
A non mathematical way to do it:
A short and simple method is, convert the double to string:
String text = String.valueOf(result);
Now you have the result in the string. Given that your requirement is that you don't want decimals, so split your string based on "." as a delimiter:
String str[] = text.split(".");
Now in str[0] you will have only the number part. so set it to the text view:
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + str[0]);
I'm sure this one works fine.
You can use DecimalFormat to format the result:
DecimalFormat df = new DecimalFormat("0.##########");
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + df.format(result));
This will print with up to 10 decimal places.
Many ways to do that, i use:
public static double round(double value, int places) {
if (places < 0)
throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
And then call:
round(yourAnswer, 2)
For BigDecimal:
http://developer.android.com/reference/java/math/BigDecimal.html
Efficient BigDecimal round Up and down to two decimals

TextViews become uneditable after reactivating activity?

So currently I am making an educational application where users can view how to solve a given problem by pressing a button. While my code works fine initially, when I hit the back button and click my View Solution button, my default layout pops up and I cannot edit the last four TextViews. Here is my code:
public class AdditionTensSolutionActivity extends Activity {
public static ArrayList<TextView> explain = new ArrayList<TextView>(3);
public static Button nextstep;
public static int onesnum1 = TensAdditionExerciseActivity.n1display % 10;
public static int onesnum2 = TensAdditionExerciseActivity.n2display % 10;
public static int onesanswer = onesnum1 + onesnum2;
public static int onesanswermod = onesanswer % 10;
public static int tensnum1 = TensAdditionExerciseActivity.n1display / 10;
public static int tensnum2 = TensAdditionExerciseActivity.n2display / 10;
public static int tensanswer = tensnum1 + tensnum2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showsolutionlayout);
TextView numrow1 = (TextView) findViewById(R.id.solproblemrow1);
TextView numrow2 = (TextView) findViewById(R.id.solproblemrow2);
TextView solution = (TextView) findViewById(R.id.solutiontextview);
TextView carryover = (TextView) findViewById(R.id.carryovernumbers);
TextView exp1 = (TextView) findViewById(R.id.explain1);
TextView exp2 = (TextView) findViewById(R.id.explain2);
TextView exp3 = (TextView) findViewById(R.id.explain3);
TextView exp4 = (TextView) findViewById(R.id.explain4);
numrow1.setText(TensAdditionExerciseActivity.n1display + "");
numrow2.setText(" " + TensAdditionExerciseActivity.n2display + " +");
explain.add(exp1);
explain.add(exp2);
explain.add(exp3);
explain.add(exp4);
nextstep = (Button) findViewById(R.id.nextstep);
for (int i = 0; i < 4; i++) {
explain.get(i).setVisibility(View.GONE);
}
solution.setVisibility(View.GONE);
carryover.setVisibility(View.GONE);
explain.get(0).setText("test");
setTextViews();
nextButtonsetOnClickListener();
}
protected void nextButtonsetOnClickListener() {
nextstep.setOnClickListener(new View.OnClickListener() {
int i = 0;
public void onClick(View v) {
explain.get(i).setVisibility(View.VISIBLE);
i++;
if (i > 2 && onesanswer < 10) {
nextstep.setClickable(false);
}
if (i > 3 && onesanswer >= 10) {
nextstep.setClickable(false);
}
}
});
}
protected void setTextViews() {
explain.get(0).setText(
"Add " + (onesnum1) + " and " + (onesnum2) + " which equals "
+ (onesanswer) + ".");
if (onesanswer >= 10) {
explain.get(1).setText(
"Since the answer is 10 or greater, 1 must carry over to the tens place and "
+ onesanswermod + " is left in the ones place.");
explain.get(2).setText(
"Add the tens place digits, " + tensnum1 + " and "
+ tensnum2
+ ". Don't forget to add the carried over 1!");
explain.get(3).setText(
"1 + " + tensnum1 + " + " + tensnum2 + " = "
+ (tensanswer + 1));
} else {
explain.get(1).setText(
"Add the tens place digits: " + tensnum1 + " and "
+ tensnum2 + ".");
explain.get(2).setText(
tensnum1 + " + " + tensnum2 + " = " + tensanswer);
}
Ah, I figured it out. I had my ArrayList set to static rather than final, but I still do not completely the entirety of my error. Would someone be willing to tell me why it made such a big difference?
A static variable / method has only one instance for the entire class. That means, that in the case of your listview, only one exists for all instances of your activity in the entire app, which is why your getting your error. Final means that it can't be initialized anywhere other than the constructor or when the variable is defined. (Difference between Static and final?).

Categories

Resources