I have two activities. The first activity display list of the users with short info. And after select some user I go to the second activity for display full info about this user. For send event I used startActivityForResult(); for receive event in socond activity and added public void onActivityResult(int requestCode, int resultCode, Intent data). After start project I send intend from first activity and I do not receive in the second :(. How I can receive sent event in second activity?
Thank you...
You implement onActivityResult in the first activity in order to get the result from the sub-activity you've started. In your sub-activity you receive the event in the onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
// Do some setup based on the action being performed.
final String action = intent.getAction();
if (action.equals()) {
}
}
I recommend that you have a look at the Notepad sample to see how things work. startActivityForResult may not be needed - startActivity should be enough. You usually don't return something from the item view to the list view.
Related
New to Android Studio. I'm creating an app project for practice and I am trying to create a Menu Activity. I want to test to see if I can mute sounds and hide the display of text (score) via a Menu UI. I get that I can use Intent to pass values back and forth between activities and that I can use those values to turn features on and off across the app.
I cannot figure out with a button and onClick how to get a variable to change so that I can pass it via Intent. I've only seen it done INSIDE the onClick. I'm trying to change the variable OUTSIDE the onClick.
Example Code:
public class Menu extends AppCompatActivity {
private boolean soundOn = true;
private Button isSoundOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
isSoundOn = findViewById(R.id.isSoundOn_button);
isSoundOn.setOnClickListener(v -> {
soundOn = false;
});
Now when I attempt to access the soundOn parameter and pass it on via Intent to another activity the value remains true, it never changes after the button is clicked.
I did figure out one trick, I can use intent and pass the value to the same activity, like so:
soundOff.setOnClickListener(v -> {
Intent intent = new Intent(Menu.this, Menu.class);
intent.putExtra("soundOn", false);
startActivity(intent);
This reloads the Activity after the button is clicked, it makes it appear as though a glitch happened as it is run, but I think that issue could be resolved via altering the transition animation...I think. However, this seems like a clumsy approach, especially in a Menu Activity that could have numerous settings to edit (sound, score, language, timer, color, background, etc.).
I get that I can have the onClick go back to the original Activity with the change, but I want to create a menu where I can have multiple selections made and then pass them all back to the original Activity.
I hope this makes sense, I know this is rather basic, but I'm new to this and my searching hasn't been able to yield a solution. Thanks.
If you are doing an intent to the same Activity you should retreive your intent on the onCreate method:
isSoundOn = intent.getBooleanExtra("soundOn", true) //true is the default parameter in case intent does not contain that key;
That way you are always checking your intent in case you need it.
You also need to use your variable in the intent; right now you are always setting it to false:
soundOff.setOnClickListener(v -> {
Intent intent = new Intent(Menu.this, Menu.class);
intent.putExtra("soundOn", soundOn);
startActivity(intent);
}
There are other solutions, for example: you can use SharedPreferences for persisting your values and then call this.recreate to recreate Activity again and avoid using intents. Then you can retreive your SharedPreferencesvalues on the onCreate method to do whatever you want.
Now when I attempt to access the soundOn parameter and pass it on via
Intent to another activity the value remains true, it never changes
after the button is clicked.
Lets start with keeping track of soundOn
When Menu activity is first launched soundOn = true
When isSound button is clicked soundOn = false
Intent intent = new Intent(Menu.this, Menu.class);
intent.putExtra("soundOn", soundOn); // false is the value that is extra.
startActivity(intent);
When MenuActivity is again launched due to the intent soundOn = true this is because of this line
private boolean soundOn = true; //<---
You are passing Extra in intent but you arent storing the intents extra value in soundOn
Thats why it is true always
to solve this use need to Get the Intent Extra that you have passed and we do it in onCreate method
private boolean soundOn = true;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Intent intent = getIntent();
if(intent != null) { // we need to get this cause when we first start our app we dont start it with any intents
soundOn = intent.getExtra("soundOn");
}
}
We have an aspx page with a form in it and we can only process this form in a browser-based environment (ie we cannot create a web service for it.
What we want to do is that we want to process this information in an android application. We want to send some initial data to this page, let the user fill it, submit the form, and then return the results to the calling activity, so we can show a proper message and act accordingly.
let me give an example for this usecase:
We are in activity A and in this activity we have a button that triggers the start of our journey:
//we are in activity A
mOurButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("additional_data_we_need", adittionalData);
startActivityForResult(intent, REQUEST_CODE);
}
});
Now we are in activity B and here, we should comunicate with that webpage that I was talking about, passing it the additionalData that is in this activity's extra bundle (it is acceptable if we do it using query strings or any other way).
After the user fills the form, and hit submit,we do some operation on it and return some results to another (web)page or in the current (web)page's postback (again it is acceptable if we use query strings, post method or any other way; whicever way that works for this senario). We get this returned result in android side and then get the result to ActivityA :
//we are in acitivity B
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
int adittionalData = getIntent().getExtras().getIntExtra("adittional_data_we_nedd");
//this is the first place that I don't know what to do
callTheWebPageAndGiveItTheData(adittionalData);
}
public void SomeListenerOfTheReturnedDataFromTheWebpage(Bundle returnedData //doesn't necessarily need to be of bundle type) {
intent intent = new Intent();
intent.putExtra("return_bundle", returnedData);
setResult(Activity.RESULT_OK, intent);
finish();
}
What can I do to achieve this goal?
Thanks in advance for your kind answers
I need to randomly generate a button and then grab elements from it from the activity that the button opens. Specifically the universal ID of a "character" that I have specified in PersistentData. (That whole class works fine, though. The problem is between this activity and the next.) The child activity has multiple activities that can call it. (There are several activities with lists made from different characters from a pool, and each list has these buttons that are shown below, which all point to the same activity that loads information from PersistentData based on the data that its supposed to pull from said button.) The following 1 block of code is in the onCreate method for this activity. (Automatically generated, I just added this in after I called the layouts from the XML file)
for (fID = 0; fID < PersistentData.fName.size(); fID++) {
if (PersistentData.fName.get(fID) != null) {
Button[] Btn = new Button[PersistentData.fName.size()];
Btn[fID].setHeight(200);
Btn[fID].setWidth(200);
Btn[fID].setTextSize(40);
Btn[fID].setText(PersistentData.fName.get(fID));
Btn[fID].setTag(fID);
Layout.addView(Btn[fID]);
Btn[fID].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int btnID = fID;
gotoActivity(v);
}
});
} else continue;
}
Here is gotoActivity(). (In the class, not onCreate)
public void gotoActivity(View view) {
Intent intent = new Intent(this, TargetActivity.class);
startActivity(intent);
intent.putExtra("btnClicked", /*IDK WHAT TO PUT RIGHT HERE*/);
}
I have put several things there, actually. Mostly, they have been various ways of declaring a variable on the creation of the button.
Here's the TargetActivity.class
public class Fighter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fighter);
Intent intent = getIntent();
Bundle bundle =
intent.getExtras(); //line ***
**
TextView viewName = (TextView) findViewById(R.id.fighterName);
viewName.setText(PersistentData.fName.get(fID));
}
}
What should I put in the other class that I should get here**? (fID) is the thing that I'm trying to get. I have tried putting and getting fID using the methods as described in the Create an Activity page from Android and it continued to give me a NullPointerException at line *** (I split the line to be precise.)
Any help is appreciated. I would not be surprised if there is a better way to do this, requiring me to scrap all my work and restart. I would prefer not to, though lol. I will be checking this post periodically throughout the day, so if you have any questions or require more detail, just post or message me. Thank you beforehand.
I think the reason you got a NullPointerException because you started the activity before persing the extra.
In the gotoActiviy, make sure the extra(s) method are called before you start the activity. that is
public void gotoActivity(View view) {
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("btnClicked", "Strings");
startActivity(intent);
}
As you can see, a string was the extra, you can put any variable type as the extra just make sure at the activity being called, the same variable type gets the extra.
as an example
String getValue = getIntent().getExtras().getString("btnClicked");
Int getValue = getIntent().getExtras().getInt("btnClicked");
/** If integer was the value activity extra */
I have one activity where the user writes in an EditText a number, then I am supposed to convert it to a string and then to an int, but I want to save that value because I am going to use it for another activity, it will be the max number of times that a botton can be pressed but I don't know how to save it from the EditText in a activity to an int in another activity.
Here the EditText of the first activity:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/texthome"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:hint="Ejemplo:15"
android:layout_weight="1"
android:textSize="20sp" />
Here the textview into int:
EditText conttext = (EditText) findViewById ( R.id.texthome );
String maxicont = conttext.getText().toString();
int maxcont = Integer.parseInt(maxicont);
UPDATE:
i get errors in:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button buttsave = (Button) findViewById(R.id.buttsave);
buttsave.setOnClickListener(new View.OnClickListener"here" {
public void onClick "here" {
Intent intent = new Intent(getApplicationContext(), GuessOne.class);
intent.putExtra("maxNumberPressed", conttext.getText());
startActivity(intent);
}
});
I get errors where i placed the "here" obviously it is not part of the code. It is only to see where the errors are.
You need to use Intents for that. A similar question was answered here:
Passing Values To Another Activity
When starting the other activity, make a bundle.
In the current activity, try:
Intent intent = new Intent(getApplicationContext(), <next activity>.class);
intent.putExtra("maxNumberPressed", editText.getText());
startActivity(intent);
Then in the next activity where you are using it, put this in onCreate method:
Bundle bundle = this.getIntent().getExtras();
String maxPressed = bundle.getString("maxNumberPressed");
Create a button with text as 'save' or something. then do:
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener{
public void onClick() {
Intent intent = new Intent(getApplicationContext(), <next activity>.class);
intent.putExtra("maxNumberPressed", editText.getText());
startActivity(intent);
}
});
How to pass data from an Activity to another can vary a lot, depending on how the Activities are related.
If you are passing data from a parent to a child Activity, you pass the information through an Intent when starting the new child Activity. Here's how you send the information:
itt = new Intent(this, ChildActivityName.class); // Create new Intent
itt.putExtra("MAX", maxcont); // Fill Intent with data
startActivity(itt, SOME_NUMBER_IDENTIFYING_THE_PARENT); // Start Activity
And here's how the receiving child Activity retrieves it:
void onCreate(Bundle savedInstanceState) {
...
Intent itt = getIntent(); // Grab the Intent created with this Activity
int maxcont = itt.getIntExtra("MAX", -1); // Retrieve data, default is -1
}
If you are passing data the other way, from a child to a parent Activity, the simplest way to pass through using startActivityForResult. The parent starts the child activity using this command:
startActivityForResult(itt, SOME_NUMBER_IDENTIFYING_THE_PARENT);
The Child then passes the information back to the parent just before it exits:
Intent itt = new Intent(); // Create new Intent
itt.putExtra("MAX_RETURN", maxcont); // Add data to the Intent
setResult(RESULT_OK, itt); // Signal to parent valid result
finish(); // End this Activity
Once the child calls finish(), the parent's onActivityResult() method will be invoked:
protected void onActivityResult(int requestCode, int resultCode, Intent itt) {
maxcont = data.getIntExtra("MAX_RETURN", -1); // defaults to -1
...
}
The Strings used in putExtra and getIntExtra are identifying keys for associated data, which are used all over the place in Android programming and beyond the scope of this question. Just make sure that the sender and the receiver of the data through the Intents use the EXACT same string!
If you need to pass information between two sibling Activities that are both active, the easiest way is through static public variables in each Activity. That's pretty basic; you should have no problem with these.
If you need to pass information between two sibling Activities that may or may not be Active, then you need to use a Broadcast/Receiver paradigm. But I think that method is overkill for what you are talking about.
I have a fragmentActivity that use startActivityForResult(intent, getCode) to call an activity that sends some files via ftp.
In the method onActivityResult(int requestCode, int resultCode, Intent data) shows the result of the operation (failure, success, no internet, etc...) using a dialog.
The dialog is called like this:
Bundle bundle = new Bundle();
bundle.putString(LLAVE_TITULO, alertTitulo);
bundle.putString(LLAVE_MENSAJE, alertMensaje);
showDialog(DIALOG_RESPUESTA, bundle);
and the onCreateDialog method is basic
#Override
protected Dialog onCreateDialog(int id, Bundle bundle)
{
Builder mAlertDialog = new AlertDialog.Builder(this);
mAlertDialog.setTitle(bundle.getString(LLAVE_TITULO));
mAlertDialog.setMessage(bundle.getString(LLAVE_MENSAJE));
mAlertDialog.setPositiveButton("Aceptar",null);
return mAlertDialog.create();
}
Everything is working ok, but I noticed when I show and dismiss the dialog really fast (the faster i can, once or twice per second) in some point the dialog doesn't show anymore until I close the activity and start it again...
What is happening here? How can I really be sure that the dialog will show?
Thanks!
activity calls onCreateDialog() one times for each dialog..
so.. I think you should use DialogInterface.OnShowListener for dialog view widgets validation