Skip to content

Instantly share code, notes, and snippets.

@uknowmeright
Created April 15, 2014 20:27
Show Gist options
  • Save uknowmeright/10769685 to your computer and use it in GitHub Desktop.
Save uknowmeright/10769685 to your computer and use it in GitHub Desktop.
How to pass variables to a new activity in Android (Android Studio)
//step 1:
import android.content.Intent;
//step 2: add to activity you want to sav variables from
Intent i = new Intent(getApplicationContext(), ActivityName.class);
i.putExtra("someVariable","variableValue");
startActivity(i);
//step 3: add to activity you want to pulll variables from
Bundle extras = getIntent().getExtras();
if (extras != null) {
String someVariable = extras.getString("someVariable");
}
@umath92
Copy link

umath92 commented Apr 18, 2015

Good stuff!

@sindhubharadwaj18
Copy link

how to pass url from one activity to another activity, kindly please help me..

here by i'll add the snippet, when i run the program, activity is changing but page is blank.

first activity,
String url = result[1].toLowerCase();
Intent i = new Intent(getApplicationContext(), choice.class);
i.putExtra("url",url);
startActivity(i);
break;
second activity,

Bundle extras = getIntent().getExtras();
if (extras != null) {
String url = extras.getString("url");
Toast t7 = Toast.makeText(getApplicationContext(),
"Visiting: "+url, Toast.LENGTH_SHORT);t7.show();
WebView view = (WebView) this.findViewById(R.id.webview1);
Toast t9 = Toast.makeText(getApplicationContext(),
"loading:"+url, Toast.LENGTH_SHORT);t9.show();
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
Toast t8 = Toast.makeText(getApplicationContext(),
"loaded:"+url, Toast.LENGTH_SHORT);t8.show();
}

please help me,
thanku in advance

@deepak9841
Copy link

So following the instructions above, I am trying to pass the variable TotalScore to new activity as such:

public void button_next(View view) {
// Do something in response to button next
Intent i = new Intent(this, DisplayMessageActivity.class);
i.putExtra("TotalScore", "0");
startActivity(i);
}
On new activity, i get an error for unidentified class called extras as such:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String TotalScore = extras.getString("TotalScore");
}

What am I doing wrong? Pleasing let me know. Thanks in advance.

@thaiksoedev
Copy link

This is can use on fragment ?? I think intent can't use in fragment ,right!

@arshad6024
Copy link

String TotalScore = (String) extras.get("TotalScore");
textview.settext(totalscore);

this can be done like this sir

@egesamichael
Copy link

This is really help full thanks @uknowmeright

@LaZyRaifur
Copy link

if i want to pass name,description and a web link.Than what should i need to do ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment