Recently I have been trying how to get the calculation of two random numbers that are shown in MainActivity to compare later with the text field and indicate if the number inserted is correct or no.
Here the code:
MainActivity.java
package com.example.miguel.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
Random random = new Random();
int randomNum = random.nextInt(101);
int randomNum2 = random.nextInt(101);
String messageRandomNum = String.valueOf(randomNum);
String messageRandomNum2 = String.valueOf(randomNum2);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textViewRandomNum = (TextView) findViewById(R.id.random_num);
textViewRandomNum.setText(messageRandomNum);
messageRandomNum2 = String.valueOf(randomNum2+ "= ");
TextView textViewRandomNum2 = (TextView) findViewById(R.id.random_num2);
textViewRandomNum2.setText(messageRandomNum2);
}
public int getCalculation(){
//Here is where I had tried to get the calculation of the same numbers that are shown in the screen
int calculation = randomNum + randomNum2;
return calculation;
}
public void sendMessage (View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayMessageActivity.java
package com.example.miguel.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
public class DisplayMessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
MainActivity mainActivity = new MainActivity();
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
int messageInt = Integer.parseInt(message);
TextView textView = new TextView(this);
textView.setTextSize(40);
//The comparison of editText and the calculation
if(messageInt == mainActivity.getCalculation()){
textView.setText("Correct!");
}else{
textView.setText("Incorrect!");
}
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
layout.addView(textView);
}
}
Always is shown that the inserted number (although it is well) shows "Incorrect!". I don't know why the calculation does a sum of random numbers, but not the random numbers than are shown in the screen.
If you don't understand something, sorry, I'm a Spanish speaker.
Regards! ;)
In MainActivity you can send calculated result
public void sendMessage (View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
int calcualtedResult=getCalculation();
intent.putInt("calcualtedResult", calcualtedResult);
startActivity(intent);
}
In DisplayMessageActivity
you can get the intent
int calculatedRes=intent.getInt("calculatedResult");
if(messageInt == calculatedRes){
textView.setText("Correct!");
}else{
textView.setText("Incorrect!");
}
wrong thing in your code is that you create an object from MainActivity in your DisplayMessageActivity. this object differ from activity that call DisplayMessageActivity and hasn't your random numbers. you must send random numbers with intent to next Activity, like EXTRA_MESSAGE.
Related
I'm new at Android Programming and I'm having issues while trying to pass a String from an activity and an other one.
I've already added the needed code in manifest file.
I would like to take "myName" from user input in MainActivity and pass it to activity_matching, but in this second file the variable is always empty.
I can't understand what I'm doing wrong, so I'm here.
package com.ium.example.packageName;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity{
String myName;
EditText edit;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
edit = findViewById(R.id.nickName);
myName = edit.getText().toString();
Button loginButton = findViewById(R.id.button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, activity_matching.class);
i.putExtra("myName", myName);
startActivity(i);
}
});
}
}
The code above is related to "MainActivity", the code below to "activity_matching"
package com.ium.example.packageName;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.snackbar.Snackbar;
import java.util.Random;
public class activity_matching extends AppCompatActivity {
float x1,x2,y1,y2;
int s;
String[] names = new String[17];
public String myName;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getSupportActionBar().hide();
setContentView(R.layout.activity_matching);
}
public boolean onTouchEvent(MotionEvent touchEvent){
switch(touchEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = touchEvent.getX();
y1 = touchEvent.getY();
break;
case MotionEvent.ACTION_UP:
x2 = touchEvent.getX();
y2 = touchEvent.getY();
Intent i = new Intent(activity_matching.this, SwipeLeft.class);
i.putExtra("num", s);
i.putExtra("arr", names);
startActivity(i);
break;
}
return false;
}
public void onBtnClick(View v) {
TextView txtHello = findViewById(R.id.txtMessage);
Intent b = getIntent();
myName = b.getStringExtra("myName");
String swipeLeft = "Swipe (a destra o sinistra) per l'argomento di discussione";
Snackbar doSwipe = Snackbar.make(v, swipeLeft, 6000);
Random rand = new Random(System.currentTimeMillis());
names = new String[]{"Name1", "Name2", "Name3", "Name4", "Name5", "Name6", "Name7", "Name8",
"Name9", "Name10", "Name11", "Name12", "Name13", "Name14", "Name15",
"Name16", "Name17"};
re:
{
s = rand.nextInt(names.length);
if (myName.equals(names[s]))
break re;
txtHello.setText(myName + " vai a parlare con " + names[s] + "!");
doSwipe.show();
}
}
}
Thanks to everyone who will answer :3
Have a nice day ^-^
It may help to try to get your intent's extra data inside of the onCreate method. I'm not sure if this will help but I was having trouble replicating your problem on my end.
in MainActivity, you assign myName before you click loginButton. Your EditText was still empty at that time. move:
myName = edit.getText().toString();
to onClick above this line
i.putExtra("myName", myName);
I have fixed the problem that I originally create this question for, but now I have a new problem. The activity gets created and it goes to my other screen when I select the button, but now the value that is suppose to get passed to the second activity always comes back as 0.
I am assuming this is the line that is causing it? How, would I fix that?
int goal = intent.getIntExtra("calorieGoal", 0);
My Main Activity.java
package net.androidbootcamp.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity {
String selection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//gets data from the user input
final EditText weight = (EditText)findViewById(R.id.bodyWeight);
final EditText age = (EditText)findViewById(R.id.yearsOld);
final EditText height = (EditText)findViewById(R.id.inchHeight);
//gets the spinner selection
final Spinner activityLevel = (Spinner)findViewById(R.id.activityLevel);
//initate the button, and set code for when the button is clicked
Button lose = (Button)findViewById(R.id.loseButton);
lose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userWeight = weight.getText().toString();
String userheight = height.getText().toString();
String userAge = age.getText().toString();
int uWeight = Integer.parseInt(userWeight);
int uHeight = Integer.parseInt(userheight);
int uAge = Integer.parseInt(userAge);
double calorieGoal;
selection = activityLevel.getSelectedItem().toString();
if(selection == "sedentary"){
double bmr = 66.47 + (6.24 * uWeight) + (12.7 * uHeight) - (6.75 * uAge);
calorieGoal = bmr * 1.2;
Intent intent = new Intent(MainActivity.this, Gain_Activity.class);
intent.putExtra("calorieGoal", calorieGoal);
startActivity(intent);
}
}
});
}
}
second activity that I am trying to send the data to
package net.androidbootcamp.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Gain_Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gain_);
Intent intent = getIntent();
int goal = intent.getIntExtra("calorieGoal", 0);
TextView texview = findViewById(R.id.calorieGoal);
texview.setText(goal);
}
}
calorieGoal is of type double, not int. You will not be able to get it via getIntExtra.
Try getDoubleExtra.
Im trying to make a weather app in android where i get input from user and then tell them the current weather. main activity looks like this
package com.example.dellinspiron.speechrecognition;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.graphics.Typeface;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView cityField, detailsField, currentTemperatureField, humidity_field, pressure_field, weatherIcon, updatedField;
Typeface weatherFont;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.button);
assert b != null;
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText c=(EditText)findViewById(R.id.city);
EditText d=(EditText)findViewById(R.id.country);
final String city=c.getText().toString();
final String country=d.getText().toString();
weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/weathericons-regular-webfont.ttf");
cityField = (TextView)findViewById(R.id.city_field);
updatedField = (TextView)findViewById(R.id.updated_field);
detailsField = (TextView)findViewById(R.id.details_field);
currentTemperatureField = (TextView)findViewById(R.id.current_temperature_field);
humidity_field = (TextView)findViewById(R.id.humidity_field);
pressure_field = (TextView)findViewById(R.id.pressure_field);
weatherIcon = (TextView)findViewById(R.id.weather_icon);
weatherIcon.setTypeface(weatherFont);
Function.placeIdTask asyncTask =new Function.placeIdTask(new Function.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: "+weather_humidity);
pressure_field.setText("Pressure: "+weather_pressure);
weatherIcon.setText(Html.fromHtml(weather_iconText));
}
});
asyncTask.execute(city, country); // having problems here
}
});
}
when i try to explicitly pass the city name and country eg asyncTask.execute("rawalpindi", "Pakistan") it works, but then if i try to pass a string obtained from the text box it doesnt.
i have tried to get output of the string and it gives the correct output but it just isnt being passed to the execute function properly. please help.
Try to trim the string using trim() method when you obtain the text from EditText as extra spaces may cause the error in the result.
I created 2 Activities, Main and Second. And I want to send text, put in the box EditText from Main to Second activity. Id of first EditText is UserName, and of the second is Description.
The code of the Main activity is:
package com.example.test;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.support.v4.app.NavUtils;
import android.content.Intent;
import android.widget.EditText;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v) {
Intent intent = new Intent(Main.this, Second.class);
intent.putExtra("username", UserName.getText().toString());
intent.putExtra("gift", Description.getText().toString());
startActivity(intent);
}
public void ButtonOneClick(View v) {
switch (v.getId()) {
case R.id.button1:
Intent i = new Intent(this, Second.class);
startActivity(i);
break;
}
}
}
Full code of the Second Activity is:
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class Second extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TextView txtInfo = (TextView)findViewById(R.id.TextOne);
String user = "ЖЫвотное";
String gift = "дырку от бублика";
user = getIntent().getExtras().getString("username");
gift = getIntent().getExtras().getString("gift");
txtInfo.setText(user + " , вам передали " + gift);
}
}
and errors:
main.java: Description cannot be resolved
main.java: UserName cannot be resolved
sorry for my english
Thanks for help
P.S. I'm studying java and programming for android just third day, please don't throw stones to me.
You'd then refer to your R class file, that is:
EditText desc = (EditText) findViewById(R.id.Description);
...
You have not included
EditText UserName = (EditText) findViewById(R.id.username);
EditText Description = (EditText) findViewById(R.id.description);
in your onCreate() method in MainActivity.
As you reference UserName and Description here refer to them as they are classes. Unless you have such classes an error will be stated because these classes can not be found (or "resolved").
You can even notice this by the syntax highlight. Do you see the words a displayed in a lght green/turquoise like Main or Intent?
public void onClick(View v) {
Intent intent = new Intent(Main.this, Second.class);
intent.putExtra("username", UserName.getText().toString());
intent.putExtra("gift", Description.getText().toString());
startActivity(intent);
}
Instead you want instances of the class EditText which you call userName and description. On these objects you can perform getText() and work your way along. :)
public void onClick(View v) {
Intent intent = new Intent(Main.this, Second.class);
EditText userName = (EditText) findViewById(R.id.username);
EditText description = (EditText) findViewById(R.id.description);
intent.putExtra("username", userName.getText().toString());
intent.putExtra("gift", description.getText().toString());
startActivity(intent);
}
Please notice I've changed the names of your variables to lowerCase starting camelCase. Though not an explicit rule it's considered good practise to start variable names with lower case letters ('userName,description,intent) while **C**lass references like (ÈditText,Main,Second`) are started with upper case letters.
you have not initialize the username & description in your java;
EditText us_name=(EditText) findViewById(R.id.user_name);
EditText us_desp=(EditText) findViewById(R.id.desp);
I am trying to use the getIntent value(score) which is retrieve from the previous activity but it seems like it is impossible. It seems that addition and subtraction under if else cannot detect score. Is there any other way?
package com.mkyong.android;
import com.mkyong.android.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class App2Activity extends Activity {
private RadioGroup radioAnswerGroup2;
private RadioButton radioAnswerButton2;
private Button btnSubmit2;
Button button2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
radioAnswerGroup2 = (RadioGroup) findViewById(R.id.radioAnswer2);
button2 = (Button) findViewById(R.id.button2);
Button button2pre = (Button) findViewById(R.id.button2pre);
Intent intent = getIntent();
final int score = intent.getIntExtra("int", -1);
final TextView result2 = (TextView) findViewById(R.id.txtResult2);
result2.setText("Result counting: " + String.valueOf(score));
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int correctId2 = (R.id.answer2b);
// get selected radio button from radioGroup
int selectedId2 = radioAnswerGroup2.getCheckedRadioButtonId();
// find the radio button by returned id
radioAnswerButton2 = (RadioButton) findViewById(selectedId2);
if (selectedId2==correctId2){
score = score + 1;
//show toast saying it is correct
//Context context = getApplicationContext();
//CharSequence text = ("You are correct!");
//int duration = Toast.LENGTH_SHORT;
//Toast toast = Toast.makeText(context, text, duration);
//toast.show();
}
else{
score = score - 1;
//toast incorrect
//Context context = getApplicationContext();
//CharSequence text = ("You are wrong but it's ok and the answer is Data Link");
//int duration = Toast.LENGTH_LONG;
//Toast toast = Toast.makeText(context, text, duration);
//toast.show();
}
Intent intent2 = new Intent(App2Activity.this, App3Activity.class);
intent2.putExtra("int", score);
startActivity(intent2);
}
});
button2pre.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, AppActivity.class);
startActivity(intent);
}
});
}
}
Move int score to be a global variable to access it in onClick. You'll also need to remove the final keyword so the value can be changed after you initialize it.
public class YourActivity extends Activity{
int score;
public onCreate( /*...etc.*/
Simply remove final keyword from :
final int score = intent.getIntExtra("int", -1);
Because a final variable can only be initialized once, either via an initializer or an assignment statement.
Read more here.