I am currently attempting to pass a string across activities. The string is used to set an image in the second activity. So the user is clicking a button in the first activity and then the appropriate image is loaded in the second activity based upon what was selected. There are three buttons in the first activity all which should send a String value to the next activity.
This is what I have in my first activity:
Button archerButton = (Button) findViewById(R.id.Button_Archer);
archerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String selection = "archer";
Bundle basket = new Bundle();
basket.putString("key", selection);
Intent i = new Intent(SelectCharacterActivity.this, LevelOneActivity.class);
i.putExtras(basket);
startActivity(i);
finish();
}
});
}
The receiving activity has the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.level_one);
ImageView img = (ImageView) findViewById(R.id.Character_Chosen);
Bundle extras = getIntent().getExtras();
String Toon = extras.getString("key");
if(Toon=="archer"){
img.setImageResource(R.drawable.archer);
}
if(Toon=="mage"){
img.setImageResource(R.drawable.mage);
}
if(Toon=="warrior"){
img.setImageResource(R.drawable.warrior);
}
}
I know that the receive if statements section works because if I manually set the value Toon the image will load. So somewhere the information is not being sent or read properly. I followed a tutorial online and but am stumped on this.
issue is Java 101. string equality test is done using the equals method.
Toon.equals("archer");
Extra tip : inverse your test to avoid null pointer exception :
"archer".equals(Toon);
Extra extra tip : considering your cases are mutually exclusive, use if else if to avoid testing all cases.
You are comparing your strings wrong,
Toon=="Anything"
will never be true, you need to use
Toon.equals("Anything")
for it to work.
EDIT:
This is true because "==" will just compare the memory addresses of the Strings, and "Anything" will just have been allocated and definitely won't match Toon. .equals however actually compares the chars in the string.
Also to test things like this try putting in a
Log.i("YourAppName", "Toon value is: " + Toon);
after
String Toon = extras.getString("key");
try to use SharedPreferences, Set it after/with the button-click and get it on 2. Activity OnCreate
If you just want to pass a simple String, you can use the following:
On sending:
Intent i = new Intent(SelectCharacterActivity.this, LevelOneActivity.class);
i.putExtra("key", selection);
startActivity(i);
On receiving:
String selection = getIntent().getStringExtra("key");
If there is no parameter with this key, selectionwill be null.
Try this
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putExtra("email", "lol#hotmail.com");
startActivity(i);
and
Intent i = getIntent();
String myemail = i.getStringExtra("email");
Furthermore, to compare String, use .equals() not ==
Related
I have an Activity called searchProcedures which allows a user to select from a listview of medical procedures. I navigate to this activity from two other activities called searchHome and describeVisit. I needed a way for searchProcedures to know which activity it should navigate back to onClick. So I pass an intent.extra from searchHome or describeVisit (key:"sentFrom" value""). Then in searchProcedures I use the following code to determine which class to navigate to.
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if(!extras.isEmpty()){
if(extras.containsKey("sentFrom")){
if(extras.getString("sentFrom") == "searchHome"){
returnIntent = new Intent(searchProcedures.this, searchHome.class);
}
else if(extras.getString("sentFrom") == "describeVisit"){
returnIntent = new Intent(searchProcedures.this, describeVisit.class);
}
else{
Log.d("failed", "the value of getString is " + extras.getString("sentFrom"));
}
}
}
Checking the Log values, the correct values are being passed to and from activity, but when I check extras.getString("sentFrom") == "searchHome/describeVisit" it comes back as false, and returnIntent remains un-initialized. I have tried putting .toString after the .getString to no avail.
1.
== compares the object references, not the content
You should use:
"searchHome".equals(extras.getString("sentFrom"))
Remeber to check blank space,...
2.
You can use a static variable in your SearchProceduresActivity to check where it comes from
SearchProceduresActivity
public static int sFrom = SEARCHHOME;
SearchHomeActivity:
Intent myIntent = new Intent(SearchHomeActivity.this, SearchProceduresActivity.class);
SearchProceduresActivity.sFrom = SEARCHHOME;
startActivity(myIntent);
DescribeVisitActivity:
Intent myIntent = new Intent(DescribeVisitActivity.this, SearchProceduresActivity.class);
SearchProceduresActivity.sFrom = DESCRIBEVISIT;
startActivity(myIntent);
SEARCHHOME, DESCRIBEVISIT value is up to you
Hope this help!
String compare should use equal not ===
I'm making an apps and I need to pass variables between two different activites. I got a TextEdit, in which I save the entry to pass it to another activity. Here's my code :
Activity "textEdit" (let call it like this...) :
if (editText_descriptionHomework.getText().toString().matches("")){
Toast.makeText(getApplicationContext(), messErr_noInput, Toast.LENGTH_LONG).show();
}
else {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
String descr = editText_descriptionHomework.getText().toString();
i.putExtra(description, descr);
finish();
startActivity(i);
}
And here's the "main activity" (in which I want to display this data) :
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("description");
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_LONG).show();
}
So, if I put nothing, I correctly have the toast saying "error blablabl", but if I put something, and I click on the button which trigg the "textEdit activity" code, it display nothing (black toast with no caracters).
Did I write something wrong guys ?
It should be:
i.putExtra("description", descr);
Yours doesn't have the quotes...
first it is better to replace this :
if (editText_descriptionHomework.getText().toString().matches(""))
by
if (editText_descriptionHomework.getText().toString().idEmpty())
that way you are making sure the EditText is empty, .match is like preg_match but for android
Now to get the value, try this instead:
String value = getIntent().getExtrasString("description");
or
String value = getIntent().getExtras().getString("description");
Last replace :
i.putExtra(description, descr);
by
i.putExtra("description",descr);
it should be like this
i.putString("description", descr);
you forgot the quotes
I use intent to send data from activity to other, when I call the 2nd activity repeatedly nothing happens,
The 1st intent:
`
Intent intent = new Intent(this, EditActivity.class);
intent.putExtra("1stNameIntent", firstName);
intent.putExtra("2ndNameIntent", lastName);
intent.putExtra("mailIntent", mail);
intent.putExtra("mobileIntent", mobile);
intent.putExtra("idIntent", intId);
startActivity(intent);`
//There is no problem with values
...
The 2nd activity:
...
`
public String firstNameHint = null;
public String lastNameHint = null;
public String mailHint = null;
public String mobileHint = null;
public int id;
public String idStr = null;`
`protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
idStr = getIntent().getExtras().getString("idIntent");
id = Integer.parseInt(idStr);
firstNameHint = getIntent().getExtras().getString("1stNameIntent");
firstName = (EditText) findViewById(R.id.firstName_ID);
firstName.setText(firstNameHint);
firstName.setHint(firstNameHint);
lastNameHint = getIntent().getExtras().getString("2ndNameIntent");
lastName = (EditText) findViewById(R.id.lastName_ID);
lastName.setText(lastNameHint);
lastName.setHint(lastNameHint);`
...
I cant find out the problem. After the first use of 2nd activity only the default values appears.
Maybe your onCreate Activity is not being called twice, depending on the 'launchMode' of the activity.
Try setting text in your onStart method.
Hope this helps.
implement onNewIntent(Intent i) in your second activity.
If the second activity has already been created (as it has), any future new intents will go to this onNewIntentMethod(...)
So, pull out your intent reading code and the code to set views into another method, and have both onCreate and onNewIntent call this new method that actually does the work.
use
intent i = getIntent();
stringvariable = i.getStringExtra("1stNameIntent");
see this Using putExtra to pass values to intent service
you should make sure that you are calling putExtra() every time you are starting the activity. because I think it only works with one intent.
also try adding Log.d() on the onCreate() of the second activity to know when it is called.
This is probably quite basic but I've only needed a use for a feature like this now. I have a button that carries out a calculation when I click on it. The output is a number. I want to put that number into a TextView on a different layout. On it's own page basically.
I can already get what I want on the same page. Just do the whole
TextView.setText();
Can anyone help me put the data onto it's own page? So when I click the button it carries out the calculation AND opens this new page to put the answer on it?
I tried putting the TextView in a new layout file and calling it via a findViewById but that gave me a force close.
Any solutions? Thanks.
EDIT: Here's the code, I'm trying to display the time on another page. See below
public void getWakeUpTime (View v) {
LocalTime localtime = new LocalTime();
LocalTime dt = new LocalTime(localtime.getHourOfDay(), localtime.getMinuteOfHour());
LocalTime twoHoursLater = dt.plusHours(2);
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
Text1.setText("Time: " + twoHoursLater.toString(formatter));
}
Right now it displays on the same page under the TextView Text1.
You can pass integer to next activity using this code:
String num;
Intent i = new Intent(this, NextActivity.class);
i.putExtra("value", num);
startActivity(i);
You can retrieve the data on next activity as shown below:
Intent i = getIntent();
String num = i.getStringExtra("value");
textview.setText("Number is: "+num);
So brother, here you want is that you have calculated a value in 1st page and you want to show it on the 2nd page am I right?
For this brother you need to pass some data(i.e. Bundle) while calling the next activity.
Here's a similar Application that I built few months back. It passes the message created in one activity to another. Hope this works for you.
The following code is from the first activity where message is created and it is bundled and sent to the next activity.
public void yourMethod(View view ){
// Fetching the message to be sent to the next activity.
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
Intent intent = new Intent(this, DisplayMessageActivity.class);
// Remember this constant(or any string you can give). to be used on other activity.
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
And this is what I did on the onCreate Method of the Activity which was called by the previous Activity.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
// save the passed message as string so that it can be displayed anywhere in this activity.
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
Hope My Program give you enough light to your solution. Hope that satisfies you.
Thanks brother.
You need to send the data as an Extra. Starting Another Activity has all the information you need.
I've two String Arrays like that ,
String[] htmlArray = {
"file:///android_asset/Pinocchio/OPS/chapter-001.xml",
"file:///android_asset/Pinocchio/OPS/chapter-002.xml",
"file:///android_asset/Pinocchio/OPS/chapter-035.xml",
"file:///android_asset/Pinocchio/OPS/chapter-035.xml"
};
String[] htmlArray1 = {
"file:///android_asset/Harry_Potter/OEBPS/part1.xhtml",
"file:///android_asset/Harry_Potter/OEBPS/part2_split_000.xhtml",
"file:///android_asset/Harry_Potter/OEBPS/part18_split_000.xhtml",
"file:///android_asset/Harry_Potter/OEBPS/part18_split_001.xhtml",
};
then, I put two ImageView in another class,
private void init() {
pino_cover = (ImageView) findViewById(R.id.pino_cover);
pino_cover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reader=new Intent(instance,ReaderScreen.class);
reader.putExtra("pino",true);
startActivity(reader);
}
});
harry_cover=(ImageView) findViewById(R.id.harry_cover);
harry_cover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reader=new Intent(instance,ReaderScreen.class);
reader.putExtra("harry",true);
startActivity(reader);
}
});
}
Then, if I click the Pino Image, I could get the data through htmlArray .
Intent i=getIntent();
Bundle b = i.getExtras();
String newText = b.
String setext=b.getString("harry");
if (newText=="pino")
pages = htmlArray;
else
pages = htmlArray1;
but if I click the Harry Image, it'd been taken to get the data through the htmlArray too. I want to get htmlArray1.
How could I get ?
You are putting only a boolean to your intent, but you could use .putExtra(mStringArray, htmlArray1); as this method exists to pass arrays through intents...?
Plus, to compare two strings in java, you MUST NOT do == but .equals(""). In your case if(newText.equals("harry))...
EDIT
Ok, in an easier version, you have that :
Intent i=getIntent();
Bundle b = i.getExtras();
String newText = b.
String setext=b.getString("harry");
if (newText=="pino")
pages = htmlArray;
else
pages = htmlArray1;
replace it by that :
Intent i=getIntent();
Bundle b = i.getExtras();
String newText = b.
String setext=b.getString("harry");
if (newText.equals("pino"))
pages = htmlArray;
else
pages = htmlArray1;
This should logically work.
I think the error lies in your using "==" to compare 2 string as mentioned above.
Please use str1.equals(str2) instead of str1 == str2.
And the answer by Sephy suggests you pass the 2 html arrays to the called activity as well. If for some reasons, the called activity can still access the 2 arrays then you can just do as you have done.
Also, in the map you passed, if you use 2 different keys (one is "harry", and one is "pino"), it seems to defeat the purpose. I suggest sth like:
on harry event:
i.putExtra("data", harry_html_array)
on pino event:
i.putExtra("data", pino_html_array)
Inside the called activity:
array = extras.getStringArray("data");