I created a 'New File' activity using
startActivityForResult(new Intent(MainActivity.this, NewFile.class),1);
The NewFile activity lets users set certain options for their text file then after clicking a button a string is saved to a static variable in my StringBuilder class and finish(); is called. How can I load this new string into the MainActivity's EditText? onCreate() is only called when the activity is first created right?
Do it on onResume or onActivityResult. It would be ideal though onActivityResult since you've used startActivityForResult, before finishing the other activity you set the setResult(int resultCode, Intent data) if you have intent to sent back or if none setResult(int resultCode). I think it is better to put the string which will be used to update your EditText as extra in the intent, then set the text using that string in onActivityResult method.
#Override
protected void onResume() {
super.onResume();
et.setText(DocumentBuilder.docText);
}
in your class NewFile.java :
String strName = "toto";
Intent intent = new Intent();
intent.putExtra("name", "toto");
setResult(1, intent);
finish();
in your MainActivity.java :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// Handle successful result
String name = intent.getStringExtra("name");
editText.setText(name);
}
}
}
refer this tutorial for more explanations
Related
I have two activities that should pass data back and forth to each other using intents. I'm not sure where to place some of the puts and gets though.
For Activity1 (MainActivity), I have a button, and on press it creates an intent, and then puts it to Activity2, then starts it using startActivity(intent).
btn.setOnClickListener((v) -> {
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("test", testClass);
startActivity(intent);
});
Then in Activity2, I get that information in the onCreate() function using getIntent.
Now what I want to do is have a button in Activity2 that will pass data to Activity1, but won't necessarily "start/show" the activity.
So I'm wondering how this can be done.
My idea is to have the following similar to before:
Activity2:
btn.setOnClickListener((v) -> {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("info", info);
});
But I'm confused about two things
Can I do this without starting the activity right away
Where would I do the getIntent call in MainActivity to retrieve this data
You can use startActivityForResult to start Activity2 and receive a result back to Activity1
Activity 1
int LAUNCH_ACTIVITY_TWO = 1;
Intent i = new Intent(this, Activity2.class);
i.putExtra("test", testClass);
startActivityForResult(i, LAUNCH_ACTIVITY_TWO);
//onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LAUNCH_ACTIVITY_TWO) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
}
}
}
Activity 2
Intent returnIntent = new Intent();
returnIntent.putExtra("result", result);
setResult(Activity.RESULT_OK, returnIntent);
finish();
Full Activity 1 code:
public class MainActivity extends AppCompatActivity {
public static int LAUNCH_ACTIVITY_TWO = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener((v) -> {
Intent i = new Intent(this, Activity2.class);
i.putExtra("test", testClass);
startActivityForResult(i, LAUNCH_ACTIVITY_TWO);
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LAUNCH_ACTIVITY_TWO) {
if(resultCode == Activity.RESULT_OK){
String result= data.getStringExtra("result");
}
}
}
}
Full Activity 2 code:
public class Activity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(getIntent().getExtras() != null) {
// Get intent extras from Activity 1
}
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener((v) -> {
Intent returnIntent = new Intent();
returnIntent.putExtra("result", result);
setResult(Activity.RESULT_OK, returnIntent);
finish();
});
}
}
You can for example create a list in activity2 to which you add the data you want to pass to activity1. Before starting activity1 you get the values out of your array and add them as extras to the input.
You can have the data added to a JSONObject and use a serializer so you don't have to add your items all by yourself.
If you want to pass your data to activity1 without starting it,so activity1 processes the data, that is not possible. Activity doesnt execute anything while you are in activity2, for such cases you use fragments.
If you use fragments you can put all data in a viewmodel which is bound to the activity instead of each fragment.
There are several ways you can achieve this pending on what type of data you're looking at passing.
If it's an entire class object then make the class parcable. You can copy and paste the class in this website http://www.parcelabler.com/ and it auto formats it for you. All you do is pass it as an intent extra.
If you're looking at data that needs an action performed on it and then passed to another activity I would suggest using and intent service. You can perform certain actions pending the intents received in the service.
If you're looking at performing certain actions only after XYZ has occurred in your application then used shared preferences. These can be accessed anywhere quite easily.
Lastly, if you're using bulk data consistently that needs to remain persistent, use a local database storage and just query when you need to.
You can use SharedPreferences or static variables/fields for that.
I have two classes Class "A" and Class "B". In class A i have declared a
String password ="admin" .Now in class B i am taking value from user and i
want to change that value of string in class A and want to store value that
user entered. How can i do that? Any help please?
class A
forgetpassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(MainActivity.this,newpassword.class);
startActivity(j);
Class B
EditText newpassword;
Button change;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_password);
newpassword = (EditText)findViewById(R.id.newpassword);
change = (Button)findViewById(R.id.chnage);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.b= newpassword.getText().toString();
Intent y= new Intent(NewPassword.this,MainActivity.class);
startActivity(y);
}
});
Use StartActivityForResult()
When you intend to get some result back from an Activity you should start activity using startActivityForResult(intent,requestcode)
Its easy Follow these steps
StartActivity
Intent i = new Intent(MainActivity.this, ForgotPasswordActivity.class);
startActivityForResult(i, 1);
Set new password in ForgotPasswordActivity
Now you are in ForgotPasswordActivity, set your new password and return back to MainActivity on Button click like this.
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent y= new Intent(NewPassword.this,MainActivity.class);
y.putExtra("someKey",newpassword.getText().toString()); //set new password
setResult(Activity.RESULT_OK, returnIntent); // set your result
finish(); // return back to MainActivity
}
});
Retrive new Password in MainActivity
Now you navigated back to MainActivty to retrieve your new password override onActivityResultMethod().
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String newPassword=data.getStringExtra("someKey");
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
Here a link on startActivityForResult()
You can send data from one activity to another in the intent, Use the putExtra() methods the intent class to pass data.Send the data like this
Intent y= new Intent(NewPassword.this,MainActivity.class);
y.putExtra("yourKey",newpassword.getText().toString())
startActivity(y);
and in the onCreate() of MianActivity you can retrieve the value using getStringExtra("yourKey") like this
Intent callingIntent = getIntent();
String password = callingIntent.getStringExtra("yourKey");
and use the password.
Or you can start the NewPassword activity for a result and get the data back in onActivityResult()
Intent newPasswordIntent = new Intent(this,NewPassword.class);
startActivityForResult(newPasswordIntent ,REQUEST_CODE);
and in the change button click handler,
Intent intent= new Intent();
intent.putExtra("yourKey",newpassword.getText().toString());
setResult(Activity.RESULT_OK, intent);
finish();
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String password = data.getStringExtra("yourKey")
}
Public static variables are easy to call, be aware that they can cause memory leaks
This can lead to context leaking or NPE when you finish the activity.
Instead use an Application class and initialize the string variable in it and with the use of getters() and setters() you can access the variable.
public class BaseApplication extends android.app.Application{
private String admin;
#Override
onCreate(...){
this.admin = "";
}
public String getAdmin(){
return this.admin;
}
public void setAdmin(String admin){
this.admin = admin;
}
}
classA:
...
((BaseApplication) getApplicationContext()).setAdmin("!mpr355!v3");
...
classB:
...
String myAdmin = ((BaseApplication) getApplicationContext()).getAdmin();
...
Also in your manifest file.
<application
android:name=".BaseApplication"
` ...>
UPDATE
Before startActivity(y);
just call
y.putExtra("pass", password);
and in your MainActivity, call getIntent().getStringExtra("pass");
Check for null pointers and you are good to go! :)
Muhammad,
There are many ways to do that and some of the listing here,
Use Broadcast receiver
Use start activity for result
Use static variable
From all of this if you want to change much time then I think broadcast receiver is good one,
Here is the example of broadcast receiver,
In your activity A register broadcast receiver with specific action,
private BroadcastReceiver brodcastRec=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent!=null && intent.getAction().equals("changePassword")){
String newPassword=intent.getStringExtra("newPassword");
//do whatever you want to do here after getting new password
}
}
};
And then after write following code in your on create of activity A
IntentFilter intentFilter=new IntentFilter("changePassword");
registerReceiver(brodcastRec,intentFilter);
And In your activity B or click event of Button
Intent intent=new Intent();
intent.setAction("changePassword");
intent.putExtra("newPassword","yourValue");
sendBroadcast(intent);
I have 2 Activity classes and 1 Non-Activity class which calls startActivityForResult() from Context passed in constructor. This is how it looks: FirstActivity -> NonActivity -> SecondActivity -> FirstActivity. In SecondActivity there is ArrayList of custom objects that needs to be passed to FirstActivity as a result. There is a problem. When onActivityResult() is called resultCode is RESULT_CANCELED, but not RESULT_OK even if setResult(RESULT_OK, intent) is called. Here is my code:
NonActivity
public void showActivity() {
Intent intent = new Intent(request, ActivityKorak.class);
intent.putExtra("data", fields);
request.startActivityForResult(intent, 1);
}
SecondActivity
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent();
intent.putExtra("data", fields);
setResult(Activity.RESULT_OK, intent);
finish();
}
FirstActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
if(resultCode != Activity.RESULT_CANCELED){
if(requestCode == 1) {
Bundle extras = intent.getExtras();
ArrayList<CustomInput> fields = (ArrayList<CustomInput>) extras.getSerializable("data");
}
}
}
You must simply remove
super.onBackPressed();
in the onBackPressed Method
What is happening is that "super.onBackPressed()" is setting the result code to "RESULT_CANCELED" and finishing your activity.
In my case, the problem was fixed by adding the SHA-1 and SHA-256 certificate fingerprints given in Android Studio (click on Gradle on the right side of the AS window, then run configurations and signingReport) to your Firebase project settings->General->SDK setup and configuration.
Update
Activity A ==> host MyFragment and from here,user started ==> ActivityB from here I need to get some value from this activty for example value integer and some String to MyFragment that hosted in ActivityA
I've MyFragment that start the activityB like this :
Intent intent = new Intent(getActivity(),NewsCommentActivity.class);
intent.putExtra("MNewsFeed", new Gson().toJson(newsFeed));
intent.putExtra("idCommentBadge",idCommentBadge);
startActivityForResult(intent,addComment);
and then when user start the activty and finish it I'm trying to pass some value from that ActivityB to MyFragment like this :
#Override
public void onBackPressed() {
super.onBackPressed();
//set ok result before finish the activity
Intent returnIntent = new Intent();
returnIntent.putExtra("idBadgeComment", idBadgeComment);
returnIntent.putExtra("totalCommentInserted", totalCommentInserted);
setResult(RESULT_OK, returnIntent);
finish();
}
and I've implement onActivityResult in MyFragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(TAG, "Result from News Comment ");
if(resultCode== Activity.RESULT_OK){
Log.i(TAG, "Result from News OK");
if(requestCode==addComment){
Log.i(TAG, "Result ReqCode Oke");
int idBadgeComment = data.getExtras().getInt("idBadgeComment");
int totalCommentInserted = data.getExtras().getInt("totalCommentInserted");
Log.i(TAG, "idComment: "+idBadgeComment);
Log.i(TAG, "Total Comment Inserted: "+totalCommentInserted);
}
}
}
also I've called onActivityResult in ActivityA that hosted MyFragment :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
/**
* call below code to get the result on the fragment
*/
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.viewpager);
fragment.onActivityResult(requestCode, resultCode, data);
}
when I try the code above I only get Log.i(TAG, "Result from News Comment "); and it didn't get the RESULT_OK value and the Intent data is null, can someone please pointed out where did I go wrong? and how to pass the value from activity to fragment ? or maybe a better way instead of using onActivityResult?
You can try putting super.onBackPressed(); as the last line since RESULT_CANCELED is returned on back press.
Just startActivity by activity.
Intent intent = new Intent(getActivity(),NewsCommentActivity.class);
intent.putExtra("MNewsFeed", new Gson().toJson(newsFeed));
intent.putExtra("idCommentBadge",idCommentBadge);
getActivity().startActivityForResult(intent,addComment);
Or put your onActivityResult to fragment.
I have 2 Activities the main activity I have called Map activity and the second that I have called Question activity when the app launch the Map activity is shown then you click the play button and the Question activity is launched with StartActivityForResult(), then when you have answered the question right the Question activity should be destroyed and created again and check the number of right answered questions and change the layout. then if you have scored 5 then Question activity should be destroyed and the Map activity will be shown but this is not happen. Here is my code
Map.class
public void OnClick_Question(View v){
Intent i = new Intent(MapActivity.this, QuestionActivity.class);
startActivityForResult(i, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(SharedPrefs.TAG, "OnActivityResult Entry");
if (resultCode == RESULT_OK) {
Log.d(SharedPrefs.TAG, "MAPActivity OnActivityResult Entry resultCode");
AssignContentView(requestCode);
}
}
Question.class
public void Next() {
Intent i = new Intent(this, QuestionActivity.class);
startActivity(i);
finish();
}
public void LevelUp() {
Log.e(SharedPrefs.TAG, "LevelUp");
super.finish();
finish(); /*This don't happen*/
}
When I see LogCat shows me this message:
09-01 11:23:03.911 901-1485/? W/ActivityManager﹕ startActivity called from finishing ActivityRecord{43386100 u0 com.example.gbb/.QuestionActivity t50 f}; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { cmp=com.example.gbb/.QuestionActivity }
Why I am doing this, is because I want to change the layout of Map Activity depending in your score.
What I'm doing wrong?
I had the same problem. I solved it by adding android:launchMode="singleTask" in the Android Manifest. Hope it works for you too.
I solved this by turning off Instant Run and re-running my code.
You can try the below code:
We need to keep the request code to be in global and static variable to access in onActivityResult method
private static final int REQUEST_CODE = 111;
public void OnClick_Question(View v){
Intent i = new Intent(MapActivity.this, QuestionActivity.class);
startActivityForResult(i, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.d(SharedPrefs.TAG, "OnActivityResult Entry");
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE:
Log.d(SharedPrefs.TAG, "MAPActivity OnActivityResult Entry resultCode");
AssignContentView(requestCode);
break;
default:
break;
}
}
}
I think there is no problem in your Map class, the problem is in second class.i.e., you need to set the RESULT_OK in that intent and then you can check if (resultCode == RESULT_OK) in onActivityResult method. Below you can find the code for that
Intent intent = new Intent();
setResult(activity.RESULT_OK, intent);
finish();
Hope this is helpful:)