Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set text an integer and get int without getting error

Tags:

java

android

I tried to get the intent from integer. The String get intent works fine and displays well but when i put the integer i get a force close error.

package kfc.project;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

public class productdetail extends Activity{

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.productdetail);
        //stuff to get intent
        Intent receivedIntent = getIntent();

        String productName = receivedIntent.getStringExtra("name");
        int productCalories = receivedIntent.getIntExtra("calories",0);

        Bundle extras = getIntent().getExtras();

        String name = extras.getString("name");

        if (name != null) {
            TextView text1 = (TextView) findViewById(R.id.servingsize);
            text1.setText(productName);

        }
        //int calories = extras.getInt("calories");

            TextView text1 = (TextView) findViewById(R.id.calories);
            text1.setText(productCalories);


    }

}
like image 433
user1072908 Avatar asked Nov 30 '22 07:11

user1072908


2 Answers

TextView text1 = (TextView) findViewById(R.id.calories);
text1.setText(""+productCalories);

Or

text1.setText(String.valueOf(productCalories));
like image 69
KK_07k11A0585 Avatar answered Dec 09 '22 19:12

KK_07k11A0585


The method setText(int) looks for a string-resource with that specific int-id. What you want to do is call the setText(String) method which takes the supplied string instead.

You can convert your int to a String in a number of ways, but I prefer this one:

        TextView text1 = (TextView) findViewById(R.id.calories);
        text1.setText(String.valueOf(productCalories));

EDIT: seems like someone already answered.

like image 29
Jave Avatar answered Dec 09 '22 18:12

Jave