I am trying to build a BMI calculator app, however, there seems to be a problem with using intent and the method getIntExtra(), as I always ended up getting the default value and not the value i passed in from another activity.
Below is my code for the first activity
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
int weight = Integer.parseInt(weightText.getText().toString());
int height = Integer.parseInt(heightText.getText().toString());
intent.putExtra(USER_WEIGHT_EXTRA, weight);
intent.putExtra(USER_HEIGHT_EXTRA, height);
startActivity(intent);
}
});
Second Activity
the reason for double height2 = (double)height/100 is to convert from cm to m.
result = (TextView)findViewById(R.id.result);
todo = (TextView) findViewById(R.id.todo);
Intent intent = getIntent();
int weight = intent.getIntExtra("USER_WEIGHT_EXTRA", extraInt);
int height = intent.getIntExtra("USER_HEIGHT_EXTRA", extraInt);
double height2 = (double)height/100;
double BMI = (weight*1.0)/(height2*height2);
if (BMI < 20.0) {
result.setText("You are: UNDERWEIGHT");
todo.setText("You Should EAT MORE");
} else if (BMI > 20.0 && BMI < 25.0) {
result.setText("You are: NORMAL WEIGHT");
todo.setText("You Should keep STAYING HEALTHY");
} else if (BMI > 25) {
result.setText("You are: OVERWEIGHT");
todo.setText("You Should EXERCISE MORE");
}
}
I am really stuck on this issue. Thank you all so much!
In first activity
Intent in = new Intent(this, OtherActivity.class);
in.putExtra("USER_WEIGHT_EXTRA", weightText.getText().toString());
in.putExtra("USER_HEIGHT_EXTRA", heightText.getText().toString());
startActivity(in);`
for otherActivity
Bundle bundle = getIntent().getExtras();
int weight = Integer.parseInt(bundle.getString("USER_WEIGHT_EXTRA"));
int height = Integer.parseInt(bundle.getString("USER_HEIGHT_EXTRA"));
Related
I am trying to learn Android Studio and my first app is a blood alcohol calculator. The user starts that app and then a new activity is started so that they can enter their weight and press ok, this returns them back to the main activity and fills in the weight text.
I use startActivityForResult and then putExtra in the second activity. The first activity crashes if I use the getExtra method, if I delete the 2 receiving lines of code then there is no crash. When I use the debugger it says NullPointerException just before it says App has stopped working
Main activity code
public class MainActivity extends Activity {
static int displayunit = 0;
static double percentage = 5.0;
static int change = 1;
static double bah;
static double vol = 25;
static double timestamp = 0;
static double w = 0;
static String we = "a";
final int rcode = 3;
final String[] units = {"Small Shot(25ml)", "Large Shot(35ml)", "Small
Port/Sherry(50ml)", "Large Port/Sherry(70ml)", "Small Wine(125ml)",
"Large
Wine(175ml)", "Small Beer Bottle(284ml)", "Half Pint(236.6ml)", "Medium
Beer Bottle(330ml)", "Can of beer(440ml)", "Large Bottle(500ml)",
"Pint(568.26ml)", "Massive Beer Bottle(660ml)"};
final int[] unitsum = {25, 35, 50, 70, 125, 175, 284, 237, 330, 440, 500,
569, 660};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setClassName("com.example.alccalc","com.example.alccalc.enterweight");
if(w ==0){
startActivityForResult(intent, rcode);
}
}
#Override
protected void onActivityResult ( int requstCode, int resultCode,
Intent intent){
if (requstCode == rcode && resultCode == RESULT_OK) {
we = getIntent().getStringExtra("weighttext");
w = Double.parseDouble(we);
}
TextView kg = (TextView) findViewById(R.id.kg);
kg.setText(we)
Second Activity
public class enterweight extends Activity {
EditText entweight;
TextView tester;
String weightstring;
#Override
protected void onCreate(Bundle State) {
super.onCreate(State);
setContentView(R.layout.activity_enterweight);
entweight = (EditText) findViewById(R.id.entweight);
tester = (TextView)findViewById(R.id.tester);
Button okweight = (Button) findViewById(R.id.okweight);
okweight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
weightstring = entweight.getText().toString();
//tester.setText(weightstring);
Intent intent = new Intent();
intent.putExtra
("weighttext", weightstring);
setResult(RESULT_OK, intent);
if (intent.hasExtra("weighttext")) {
finish();
}
}
});
}
}
The error is here getIntent();
Since you are using the onActivityResult ( int requstCode, int resultCode,
Intent intent) method, you can find your extras in the variable intent. The method getIntent() returns the intent that is used to start the activity. In your case it is null.
Use:
we = intent.getStringExtra("weighttext");
instead of
we = getIntent().getStringExtra("weighttext");
Better:
Bundle extras = intent.getExtras();
if (extras != null) {
String result = extras.getString("weighttext");
.....
}
Try this in your receiving code
Intent intent= getIntent();
Bundle b = intent.getExtras();
if(b != null)
we = b.getString("weighttext");
You are calling getIntent() to get the result data. getIntent() is an activity method that returns an intent that is used to start the activity. You should use the intent variable that is passed on onActivityResult method.
if (requstCode == rcode && resultCode == RESULT_OK) {
we = intent.getStringExtra("weighttext");
w = Double.parseDouble(we);
}
I'm developing an app for android, and currently the only thing it does is calculate grades. There's two input boxes, one that takes the current grade, and another that takes a possible exam grade, and then it tells you the final grade. However, when there is no value in at least one of those boxes, it crashes. I tried to make an if statement to detect if the final value was null, but that didn't work. Here's my code:
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText grade = (EditText) findViewById(R.id.grade1);
EditText exam = (EditText) findViewById(R.id.grade2);
String stringGrade = (grade.getText().toString());
String stringExam = (exam.getText().toString());
double finalResult = (Double.parseDouble(stringGrade) * .8) + (Double.parseDouble(stringExam) * 0.2);
String finalResultString = String.valueOf(finalResult);
if (finalResultString == null){
finalResultString = "0";
} else {
intent.putExtra(EXTRA_MESSAGE, finalResultString);
startActivity(intent);
}}
and here's the code that renders it:
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView1 = new TextView(this);
textView1.setTextSize(30);
textView1.setText("Your final would be " + message);
setContentView(textView1);
Just for reference, the .8 and .2 is because the current grade is weighted at 80%, and the exam is weighted at 20%. How can I make it so it won't crash when nothing is put into the boxes?
usernameEditText.getText().toString(); would not return null. It will return an empty string. What you can do before calculating finalResult is to check stringGrade and stingExam are non-empty and numerical values and if one is not then stop the operation. i.e.
String stringGrade = (grade.getText().toString());
String stringExam = (exam.getText().toString());
if (stringGrade.isEmpty() || stringExam.isEmpty()) {
Toast.makeText(this, "Invalid values", Toast.LENGTH_SHORT);
return;
}
try this:
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText grade = (EditText) findViewById(R.id.grade1);
EditText exam = (EditText) findViewById(R.id.grade2);
String stringGrade = (grade.getText().toString());
String stringExam = (exam.getText().toString());
if(stringGrade.equals("") ){
stringGrade = "0";
}
if(stringExam.equals("") ){
stringExam= "0";
}
double finalResult = (Double.parseDouble(stringGrade) * .8) + (Double.parseDouble(stringExam) * 0.2);
String finalResultString = String.valueOf(finalResult);
if (finalResultString == null){
finalResultString = "0";
} else {
intent.putExtra(EXTRA_MESSAGE, finalResultString);
startActivity(intent);
}}
How to pass value of textview form one activity going to the other activity?
I have a scoring on my game that is shown on a textview and after it increment it will intent to the next activity. but the value of score from the first activity doesn't show on the textview of the second activity.
this is my code for my first activity
final TextView score2 = (TextView) findViewById(R.id.tvscore2);
Button page1 = (Button) findViewById(R.id.btnDog);
page1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText etDog1 = (EditText) findViewById(R.id.etDog);
String Dog = etDog1.getText().toString();
if (Dog.equalsIgnoreCase("dog")) {
global.score += 10;
score2.setText(String.valueOf(global.score));
Toast.makeText(getApplicationContext(), "Correct",
Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(view.getContext(),
sound1_3pig.class);
startActivityForResult(myIntent, 0);
} else if (global.score <= 0) {
global.score += 0;
score2.setText(String.valueOf(global.score));
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
} else {
global.score -= 5;
score2.setText(String.valueOf(global.score));
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
I want to display the result of the score activity 1 to the textview of the second activity
this is my second activity
final TextView score1 = (TextView) findViewById(R.id.tvscore1);
Button page1 = (Button) findViewById(R.id.btnCat);
page1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText etCat = (EditText) findViewById(R.id.etCat);
String Cat = etCat.getText().toString();
if (Cat.equalsIgnoreCase("cat")) {
global.score += 10;
score2.setText(String.valueOf(global.score));
Toast.makeText(getApplicationContext(), "Correct",
Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(view.getContext(),
sound1_3pig.class);
startActivityForResult(myIntent, 0);
finish();
} else if (global.score <= 0) {
global.score += 0;
score2.setText(String.valueOf(global.score));
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
} else {
global.score -= 5;
score2.setText(String.valueOf(global.score));
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
As your second activity inflates a new layout, you need to explicitly pass your value from the first to the second activity and initialize it's TextView using this value.
Activity 1:
void goToSecondActivity() {
String value = mTextView.getText();
Intent in = new Intent(getActivity(), YourSecondClass.class);
in.putExtra("score", value);
startActivity(in);
}
Activity 2:
void onCreate(Bundle bundle) {
...
String score = getIntent().getStringExtra("score", "No score.");
mTextView.setText(score);
}
Use something like this.
Activity 1:
Intent i = new Intent(getActivity(), Activity2.class);
i.putExtra("Score", 20);
startActivity(i);
Activity 2:
Intent i = getIntent();
int score = i.getIntExtra("Score", 0);
My answer is also similar to what the others have suggested. try this, I have added some extra statements within your code(I presumed you want to send the value of variable score to the next activity, you can replace it with the variable you want to send) :
first activity:
score2.setText(String.valueOf(score));
Toast.makeText(getApplicationContext(), "Correct",
Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(this,
sound1_3pig.class);
myIntent.putExtra("Score", global.score);
startActivityForResult(myIntent, 0);
second activity:
put this in the onCreate() method of the second activity:
Intent intent = getIntent();
int score = intent.getIntExtra("Score",0);
so now you will get the value of score from the previous activity in the second activity. then you can set it in the textView you want to display it in by calling
textView.setText(score);
I'm trying to encode a String in QR Code wusing ZXING library. this is the lines of code corresponding to this :
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.google.zxing.client.android.ENCODE");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra("ENCODE_TYPE", "TEXT_TYPE");
intent.putExtra("ENCODE_DATA","HELLO WORLD");
startActivityForResult(intent, 0);
}
});
}
After clicking on the button i have a "force close"
After looking in some websites, we say that it works just with these lines. unfortunately, it isnt for me.
PLEASE Can you give some advices to make it working. OR if you have other way to integrate a QRCode generator to my ANDROID App it will be great too.
Enzo, this is another way to get it working, try this:
private void encode(String uniqueID) {
// TODO Auto-generated method stub
BarcodeFormat barcodeFormat = BarcodeFormat.QR_CODE;
int width0 = 500;
int height0 = 500;
int colorBack = 0xFF000000;
int colorFront = 0xFFFFFFFF;
QRCodeWriter writer = new QRCodeWriter();
try
{
EnumMap<EncodeHintType, Object> hint = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hint.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = writer.encode(uniqueID, barcodeFormat, width0, height0, hint);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++)
{
int offset = y * width;
for (int x = 0; x < width; x++)
{
pixels[offset + x] = bitMatrix.get(x, y) ? colorBack : colorFront;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
ImageView imageview = (ImageView)findViewById(R.id.qrCode);
imageview.setImageBitmap(bitmap);
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This line:
Intent intent = new Intent("com.google.zxing.client.android.ENCODE");
identifies the Activity you are calling with the Intent. In order for it to work that Activity must exist on the device. If you haven't implemented the Activity inside your project (that is, there is no class ENCODE inside your com.google.zxing.client.android package) then you will be calling an external application from yours. If there are no applications on the device/emulator that respond to the broadcast for com.google.zxing.client.android.ENCODE then you are not going to get anywhere with this solution.
You either need to install an application that will respond to com.google.zxing.client.android.ENCODE or find another way to do it.
It is possible to generate the barcode yourself using zxing libraries within your application. Have a look at the project here at Google Code for some downloads. This will remove your dependancy on an external application existing, providing a more thorough solution.
Rather than Zxing library you are also able to get the string from QRCode by using intents as below :
try {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes
startActivityForResult(intent, 0);
} catch (Exception e) {
Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
startActivity(marketIntent);
}
And on activity result as below :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
Log.v("MESSAGE: ", contents);
Intent in = new Intent(MainActivity2.this,MainActivity3.class);
Bundle b3= new Bundle();
b3.putString("content",contents);
in.putExtras(b3);
startActivity(in);
}
}
}
It may be helpful for you.
Thank You.
simple program: 2 buttons (previous/next) and a textview to show text.
by intent I created an Index (inside a method)
private void index(){
Intent i = new Intent(this, Index.class);
startActivityForResult(i, 1);
}
Index.class (with 3 buttons):
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String result = "1";
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
}
});
Main.class
String value = "1";
final String prog1[] = new String[16];
final String prog2[] = new String[105];
final String prog3[] = new String[66];
int a;
int b;
int c=3;
int array1start = 0; int array1end = 15;
int array2start = 0; int array2end = 105;
int array3start = 0; int array3end = 65;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (value.equals("1")){
a = array1start;
b = array1end;
prog=prog1;
}
else if (value.equals("2")){
a = array2start;
b = array2end;
prog=prog2;
textView1.setText(""+prog[a]);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
value=result;
Toast toast2=Toast.makeText(this,"value: "+value,Toast.LENGTH_LONG);
toast2.show();
}
if (resultCode == RESULT_CANCELED) {
//Write your code on no result return
}}
}//onAcrivityResult
at this point, choosen choice in index class should be change a result string to "value" string in main class
private void index(){
Intent i = new Intent(this, Index.class);
startActivityForResult(i, 1);
}
my textview take data from array1 or array2 by index class
so, I dont' understand how update textview (because index value is correct).
thanks for the help
Put you code into function onActivityResult
if (value.equals("1")){
a = array1start;
b = array1end;
prog=prog1;
}
else if (value.equals("2")){
a = array2start;
b = array2end;
prog=prog2;
textView1.setText(""+prog[a]);