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);
Related
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.
I want to fill the TextView of another activity based on preference on checkBox event but its working please help me to sort the issue..It is forcefully stopping.Please help in the if else statement part .what we need to write in activity 2 to select based on the checkBox in activity 1
Activity 1:
package com.example.rajatanurag.shoppingsites;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
public class Book extends AppCompatActivity {
Button b1,b2;
public static CheckBox cb1,cb2,cb3;
TextView tv1,tv2,tv3;
SharedPreferences sp1;
ImageView iv1,iv2,iv3;
String x,y,z;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
b1=(Button)findViewById(R.id.b1);
b2=(Button)findViewById(R.id.b2);
cb1=(CheckBox)findViewById(R.id.cb1);
cb2=(CheckBox)findViewById(R.id.cb2);
cb3=(CheckBox)findViewById(R.id.cb3);
tv1=(TextView)findViewById(R.id.tv4);
tv2=(TextView)findViewById(R.id.tv2);
tv3=(TextView)findViewById(R.id.tv3);
iv1=(ImageView)findViewById(R.id.iv1);
iv2=(ImageView)findViewById(R.id.iv2);
iv3=(ImageView)findViewById(R.id.iv3);
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
}
public void OnClick1(View view)
{
SharedPreferences.Editor editor = sp1.edit();
if(cb1.isChecked()==true) {
editor.putString("price1", tv1.getText().toString());
editor.putBoolean("x",true);
}
if(cb2.isChecked()==true)
{
editor.putString("price2",tv2.getText().toString());
editor.putBoolean("y",true);
}
if(cb3.isChecked()==true)
{
editor.putString("price3",tv3.getText().toString());
editor.putBoolean("z",true);
}
editor.commit();
Intent i=new Intent(this,MyCart.class);
startActivity(i);
}
}
2.Activity
package com.example.rajatanurag.shoppingsites;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MyCart extends AppCompatActivity {
SharedPreferences sp1;
TextView tv4,tv5,tv6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_cart);
tv4=(TextView)findViewById(R.id.tv4);
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
if(Book.cb1.isChecked()==true){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
if(Book.cb1.isChecked()==true){
String price21=sp1.getString("price2","");
tv5.setText(price21);
}
if(Book.cb1.isChecked()==true){
String price31=sp1.getString("price3","");
tv6.setText(price31);
}
}
}
You shouldn't be using static variables for view members because you might get memory leaks. Also the views you are referencing are destroyed when activity is destroyed, so they are not accessible in your second activity. You can send checkboxes checked values as intent extras.
Put this in your Activity 1 in OnClick1() method:
Intent i=new Intent(this,MyCart.class);
i.putExtra("cb1", cb1.isChecked());
i.putExtra("cb2", cb2.isChecked());
i.putExtra("cb3", cb3.isChecked());
startActivity(i);
This is how you get values in Activity 2 (in onCreate() method):
Intent intent = getIntent();
if(intent.getBooleanExtra("cb1", false)){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
if(intent.getBooleanExtra("cb2", false)){
String price21=sp1.getString("price2","");
tv5.setText(price21);
}
if(intent.getBooleanExtra("cb3", false)){
String price31=sp1.getString("price3","");
tv6.setText(price31);
}
public void OnClick1(View view)
{
if(view.getID() == R.id.cb1)
{
if(cb1.isChecked())
editor.putBoolean("x",true);
else
editor.putBoolean("x",false);
}
}
In your second activity
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
boolean isChecked = sp1.getBoolean("x", false);
if(isChecked){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
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.
This one is destroying my brain, when you enter the activity you can click the paypal button and you go into the paypal activity fine. If you cancel the paypal activity you are brought back to the original activity. From here if you click the button again nothing happens. I tried printing a basic message to console in the OnClick method and it didn't even show, it doesn't seem to be registering the clicks. I'm Assuming the problem has nothing to do with the layout xml file or the manifest file. I would post an image but i cant because im new, all you need to know is that its a checkout screen with a paypal button really.
Thanks in advance,
Hugh.
package com.cit.datastructuretesting;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalPayment;
public class StoreItemInterface extends Activity implements OnClickListener, OnKeyListener
{
Double subtotal, shipping, total;
EditText etItemQuantity;
TextView tvItemSubtotal, tvItemTotal;
DecimalFormat decFormat = new DecimalFormat("#.##");
PayPal ppObj;
CheckoutButton launchPayPalButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.storeiteminterface);
ImageView ivItemImage = (ImageView) findViewById(R.id.ivItemImage2);
TextView tvItemTitle = (TextView) findViewById(R.id.tvItemTitle2);
TextView tvItemDescription = (TextView) findViewById(R.id.tvItemDescription2);
etItemQuantity = (EditText) findViewById(R.id.etItemQuantity);
tvItemSubtotal = (TextView) findViewById(R.id.tvItemSubtotal);
TextView tvItemShipping = (TextView) findViewById(R.id.tvItemShipping);
tvItemTotal = (TextView) findViewById(R.id.tvItemTotal);
subtotal = Main.appData.getStore().getStoreCatagory(StoreInterface.currentCatagory).getStoreItem(StoreItemsInterface.currentItem).getPrice() * Integer.parseInt(etItemQuantity.getText().toString());
shipping = Main.appData.getStore().getStoreCatagory(StoreInterface.currentCatagory).getStoreItem(StoreItemsInterface.currentItem).getShippingPrice();
total = subtotal + shipping;
ivItemImage.setImageBitmap(Main.appData.getStore().getStoreCatagory(StoreInterface.currentCatagory).getStoreItem(StoreItemsInterface.currentItem).getImageBitmap());
tvItemTitle.setText(Main.appData.getStore().getStoreCatagory(StoreInterface.currentCatagory).getStoreItem(StoreItemsInterface.currentItem).getTitle());
tvItemDescription.setText(Main.appData.getStore().getStoreCatagory(StoreInterface.currentCatagory).getStoreItem(StoreItemsInterface.currentItem).getDescription());
tvItemSubtotal.setText("€" + decFormat.format(subtotal));
tvItemShipping.setText("€" + decFormat.format(shipping));
tvItemTotal.setText("€" + decFormat.format(total));
etItemQuantity.setOnKeyListener(this);
//setup paypal stuff
ppObj = PayPal.initWithAppID(this.getBaseContext(), "APP-80W284485P519543T", PayPal.ENV_SANDBOX);
launchPayPalButton = ppObj.getCheckoutButton(this, PayPal.BUTTON_278x43, CheckoutButton.TEXT_PAY);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.bottomMargin = 10;
launchPayPalButton.setLayoutParams(params);
((RelativeLayout)findViewById(R.id.paypalLayout)).addView(launchPayPalButton);
launchPayPalButton.setOnClickListener(this);
}
#Override
public void onClick(View arg0)
{
if(arg0.getId() == launchPayPalButton.getId())
{
System.out.println("TEST");
if(!tvItemTotal.getText().toString().equals("---"))
{
PayPalPayment newPayment = new PayPalPayment();
newPayment.setSubtotal(BigDecimal.valueOf(total));
newPayment.setCurrencyType("EUR");
newPayment.setRecipient("Cape_1328492032_biz#mycit.ie");
newPayment.setMerchantName("Cape Clear App");
Intent paypalIntent = PayPal.getInstance().checkout(newPayment, StoreItemInterface.this);
StoreItemInterface.this.startActivityForResult(paypalIntent, 1);
}
else
{
Toast.makeText(StoreItemInterface.this, "Invalid Quantity!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2)
{
if(etItemQuantity.getText().toString() != null && !etItemQuantity.getText().toString().trim().equals("") && !etItemQuantity.getText().toString().trim().equals("0"))
{
subtotal = Main.appData.getStore().getStoreCatagory(StoreInterface.currentCatagory).getStoreItem(StoreItemsInterface.currentItem).getPrice() * Integer.parseInt(etItemQuantity.getText().toString());
total = subtotal + shipping;
tvItemSubtotal.setText("€" + subtotal);
tvItemTotal.setText("€" + decFormat.format(total));
}
else
{
tvItemSubtotal.setText("---");
tvItemTotal.setText("---");
}
return false;
}
}
Try launchPayPalButton.updateButton() after the stuff you do when onClick()
https://www.x.com/developers/paypal/forums/paypal-mobile-xspace/android-interrupting-paypal-onclick-event#answer-203333
In case you are still looking for an answer, I have one
If you have a look at getCheckoutButton method, it takes Context as parameter, so when the Activity is for e.g. say Paused which happens when you start another Activity, the instance of the CheckoutButton is lost somehow.
I fixed is by using updateButton method in onResume of the Activity
#Override
protected void onResume() {
/**
* The CheckoutButton has to be updated each time the Activity is
* resumed, otherwise the onClickListener of CheckoutButton will not work
**/
if (mCheckOutBtn != null && (mCheckOutBtn instanceof CheckoutButton))
mCheckOutBtn.updateButton();
super.onResume();
}
This works considering you initialized PayPal library and CheckoutButton in onCreate of Activity.
I am trying to have it so when you click one of the answeers (Q1A1 or Q1A2) it will add a number of points to the testScore int so I can then later call that in a later class so the score they got would be posted there. Thanks to anyone who helps in advance!
here's my code,
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Test extends Activity implements OnClickListener
{
TextView Q1A1;
TextView Q1A2;
TextView test;
public static final String PREFS_NAME = "MyPrefsFile";
public static final int testScore = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Q1A1 = (TextView) findViewById(R.id.Q1A1);
Q1A2 = (TextView) findViewById(R.id.Q1A2);
Q1A1.setOnClickListener(this);
Q1A2.setOnClickListener(this);
test = (TextView) findViewById(R.id.test);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
test.setText(settings.getString("YourScore", "No Score"));
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.Q1A1:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YourScore", (testScore + 10));
editor.commit();
//Intent FinalScore = new Intent(this, FinalScore.class);
//startActivity(FinalScore);
break;
case R.id.Q1A2:
break;
}
}
}
thanks for the help
You are are saving your score as an int but calling it as a string.
Change
test.setText(settings.getString("YourScore" , "No Score"));
To
test.setText(""+settings.getInt("YourScore" , 0));