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.
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 an activity with two variables
int cifracero
and
int cifrauno
I want to pass those variables to a fragment to be shown in some TextViews as the result of the multiplication made in the previous screen...like a "Congratulations, the multiplication was..."
I need to do something like a bundle to pass the variables as arguments of the second screen, in this case a fragment.
And then I have a third variable resultado which is the result of the multiplication of cifracero and cifrauno
This is the activity code
package com.example.aprendelastablasdemultiplicar;
import androidx.activity.ComponentActivity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.ListFragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
public class quizingresar extends ComponentActivity {
private EditText cifracero;
private EditText cifrauno;
private TextView resultado;
private Button calcular;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quizingresar);
cifracero = (EditText) findViewById(R.id.cifracero);
cifrauno = (EditText) findViewById(R.id.cifrauno);
resultado = (TextView) findViewById(R.id.resultado);
calcular = (Button)findViewById(R.id.calcular);
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int multiplicationResult = multiplicarValores();
resultado.setText(Integer.toString(multiplicationResult));
}
#Override
public void afterTextChanged(Editable s) {
}
};
cifracero.addTextChangedListener(textWatcher);
cifrauno.addTextChangedListener(textWatcher);
calcular.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCongratulationsCalcular();
}
});
}
private int multiplicarValores() {
final String strnumber0 = cifracero.getText().toString();
final String strnumber1 = cifrauno.getText().toString();
int number0 = 0;
int number1 = 0;
try {
number0 = Integer.parseInt(strnumber0);
} catch (NumberFormatException e) {
}
try {
number1 = Integer.parseInt(strnumber1);
} catch (NumberFormatException e) {
}
return number0 * number1;
}
public void openCongratulationsCalcular(){
Intent intent = new Intent(this, congratulationscalcular.class);
startActivity(intent);
}
}
I need to recover the variables from the previous screen to be shown in the new fragment screen
You can have both of your fragments share the data between them by having them both under the same viewmodel, as shown here.
If you are going to be swapping screens, I think a very efficient solution would be to pass the desired data from one (screen) fragment to another using attributes in your Navigation Graph. Shown here.
Take a look at Data-Binding as well if you'd like, might be useful.
Intent intent = new Intent(this, DisplayMessageActivity.class);
String result = resultado.getText().toString();
intent.putExtra("EXTRA_MESSAGE", result);
startActivity(intent);
to get the message that was passed by the first activity
Intent intent = getIntent();
String message = intent.getStringExtra("EXTRA_MESSAGE");
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.
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 have a problem with the concatenation of the strings that I will I enter.
This is the class:
package com.isma.multisitesearch.Siti;
import com.isma.multisitesearch.R;
import com.isma.multisitesearch.Webviews.GoogleWebView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Google extends Activity implements OnClickListener {
private String TAG_ACT = "Caricamento ricerca";
public EditText googletext;
private Button googlebutton;
private String googleurl = "https://www.google.it/search?q=";
public static String newgoogleurl;
public String space = " ";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.google);
googletext = (EditText) findViewById(R.id.googletext);
googlebutton = (Button) findViewById(R.id.googlebutton);
googlebutton.setOnClickListener(this);
newgoogleurl = googleurl + googletext.getText().toString();
newgoogleurl.replaceAll(space, "%20");
System.out.println(newgoogleurl);
}
#Override
public void onClick(View v) {
Log.v(TAG_ACT, "in corso");
Intent intent = new Intent(Google.this, GoogleWebView.class);
startActivity(intent);
}
}
And this is the WebView to which I want to get the concatenation:
package com.isma.multisitesearch.Webviews;
import com.isma.multisitesearch.R;
import com.isma.multisitesearch.Siti.Google;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class GoogleWebView extends Activity {
private WebView googlewebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.googlewebview);
googlewebview = (WebView) findViewById(R.id.googlewebview);
googlewebview.getSettings().setJavaScriptEnabled(true);
googlewebview.getSettings().setLoadsImagesAutomatically(true);
googlewebview.setWebViewClient(new WebViewClient());
googlewebview.loadUrl(Google.newgoogleurl);
}
}
The app works fine but when I go to write the search text in the EditText, the google but I get the main page where you can enter the search instead of the url with already entered the search text.
I hope you know to help me, after this I was able to run the app.
Try this:
#Override
public void onClick(View v) {
newgoogleurl = googleurl + googletext.getText().toString();
newgoogleurl = newgoogleurl.replaceAll(space, "%20");
Log.v(TAG_ACT, "in corso");
Intent intent = new Intent(Google.this, GoogleWebView.class);
startActivity(intent);
}
Note that
newgoogleurl.replaceAll(space, "%20");
has no effect, you need to code:
newgoogleurl = newgoogleurl.replaceAll(space, "%20");
Have a look here:
http://javarevisited.blogspot.it/2011/12/java-string-replace-example-tutorial.html
Try below code:
String url;
url = googleurl+googletext.getText().toString();
if( url.contains(" ")){
newgoogleurl=url.replaceAll(" ","%20");
}else{
newgoogleurl=url;
}
This is containing validation part also.
Strings are immutable. That means that you cannot modify an instance of String, and need to create a new one each time you want to modify it.
In your case, replaceAll does not modify the String you call it on, but rather returns a new String with your modification applied.
Which is why you need to affect the returned value to the reference of your String.
newgoogleurl = newgoogleurl.replaceAll(space, "%20");
Moreover, you should read the documentation for replaceAll, because I don't think it does what you want. You probably want to use replace.