Start intent activity back to same activity - android

I am creating an application, surprising I know, and using a quick back button to return the user to a previous listing. The code below is the intent portion that starts the activity. Now it is sending the activity back to itself with an "LvPos" variable to determine which position it just re-start itself at.
Spinner spinMe = (Spinner)findViewById(R.id.spinner1);
Intent backIntent = new Intent(null, null, getBaseContext(), MainActivity.class);
int itemSelected = spinMe.getSelectedItemPosition();
backIntent.putExtra("LvPos", itemSelected);
startActivity(backIntent);
Now the code below is the reference in the onCreate method that gets teh LvPos variable. The problem is, when I get to this portion, the LvPos is null. I have the same code for various other intents and all work fine. If anyone can see any glaring issues, let me know as I have to be severely overlooking something.
int positionID = 0;
Bundle extras = getIntent().getExtras();
if (extras != null){
String LvPosBundle = extras.getString("LvPos");
if (LvPosBundle != null)
positionID = Integer.parseInt(LvPosBundle);
}
Thank you in advance.

You are Using the putExtra(String, int) when you are putting the extra.
When retrieving you use:
extras.getString("LvPos");
instead use:
extras.getInt("LvPos");
Store that in an integer instead of string. Then you also don't have to do the parseInt.
Hope this Helps.
-Travis

Related

Intent Extras.getString() not comparing correctly -- Android

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 ===

is there a way in android studio to call a single activity from couple of other activities?

please help .
Im trying to get access to one specific activity from two other activity so I wont write multiple code .
I send from those different activities the same type of "putExtra" but with different values to identify the source of the activity it came from.
I would like if someone could tell me what Im doing wrong.
Sorry and thanks in advance ...
Is this what you're looking for?
Activity1
Intent i = new Intent(Activity1.this, DestinationActivity.class)
i.putExtra("OriginActivity", "Act1")
startActivity(i)
Activity2
Intent i = new Intent(Activity2.this, DestinationActivity.class)
i.putExtra("OriginActivity", "Act2")
startActivity(i)
DestinationActivity
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras != null) {
if(extras.getString("OriginActivity").equals("Act1")){
// you came from Activity 1
}else if(extras.getString("OriginActivity").equals("Act2")){
// you came from Activity 2
}
etc.
You don't need to send extra values to identify the calling Activity, there's a method called getCallingActivity() which can help you.
But it would only return a non null value if you have invoked your Activity through startActivityForResult()
Here is the sample code:
ComponentName callingActivity = getCallingActivity();
if (callingActivity != null)
{
String activityName = callingActivity.getShortClassName();
if (activityName.endsWith("INVOKING_ACTIVITY_NAME"))
{
//do stuff
}
}

Passing variables through activities

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

Passing a String value across Activities?

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 ==

How to get results in new activity from the previous activity results in android?

I have two activities say X and y. In x there is edittext n 6 radiobutton if user clicks button the value gets retrieved from database based on input from edittext n radiobutton. the values should be displayed in next activity y. can yu pls help in giving snippet..thanks in advance
You can easily pass data from one activity to another using Bundle or Intent.
Lets look at the following example using Bundle:
//creating an intent to call the next activity
Intent i = new Intent("com.example.NextActivity");
Bundle b = new Bundle();
//This is where we put the data, you can basically pass any
//type of data, whether its string, int, array, object
//In this example we put a string
//The param would be a Key and Value, Key would be "Name"
//value would be "John"
b.putString("Name", "John");
//we put the bundle to the Intent
i.putExtra(b);
startActivity(i, 0);
In "NextActivity" you can retrieve the data using the following code:
Bundle b = getIntent().getExtra();
//you retrieve the data using the Key, which is "Name" in our case
String data = b.getString("Name");
How about using only Intent to transfer data. Lets look at the example
Intent i = new Intent("com.example.NextActivity");
int highestScore = 405;
i.putExtra("score", highestScore);
In "NextActivity" you can retrieve the data:
int highestScore = getIntent().getIntExtra("score");
Now you would ask me, whats the difference between Intent and Bundle, they seems like
they do exactly the same thing.
The answer is yes, they both do exactly the same thing. But if you want to transfer alot of data, variables, large array you would need to use Bundle, as they have more methods for transferring large amount of data.(i.e. If your only passing one or two variable then just go with Intent.
You should put the values into a bundle and pass that bundle to the intent that's starting the next activity. Sample code is in the answer to this question: Passing a Bundle on startActivity()?
Bind the data that you would like to send with the Intent you are calling to go to the next activity.
Intent i = new Intent(this, YourNextClass.class);
i.putExtra("yourKey", "yourKeyValue");
startActivity(i);
In YourNextClass activity, you can get the passed data by using
Bundle extras = getIntent().getExtras();
if (extras != null) {
String data = extras.getString("yourKey");
}

Categories

Resources