TWO ways data binding between activities - java

I've 2 activities, and need the main Activity to send some data to the second Activity then the second activity analyze this data and send response back, so I've the below 2 codes:
Main Activity:
import static tk.zillion.mobile.SecondActivity.EXTRA_STUFF;
public class MainActivity extends Activity {
private static int PICK_CONTACT_REQUEST = 0;
private static final int SECOND_ACTIVITY_RESULT_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Start the SecondActivity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, "my text");
startActivityForResult(intent, SECOND_ACTIVITY_RESULT_CODE);
finish();
}
// This method is called when the second activity finishes
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(this, "I'm the Main activity", Toast.LENGTH_SHORT).show();
// check that it is the SecondActivity with an OK result
if (requestCode == SECOND_ACTIVITY_RESULT_CODE) {
if (resultCode == RESULT_OK) {
// get String data from Intent
String returnString = data.getStringExtra(EXTRA_STUFF);
// set text view with string
Toast.makeText(this, "I'm the Main activity", Toast.LENGTH_SHORT).show();
}
}
}
and the Second Activity is as below:
public class SecondActivity extends Activity {
static final String EXTRA_STUFF = "tk.zillion.mobile.EXTRA_STUFF";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent();
String s = getIntent().getStringExtra(Intent.EXTRA_TEXT);
Toast.makeText(this, "I'm the second activity " + s , Toast.LENGTH_SHORT).show();
Bundle basket =new Bundle();
basket.putString(EXTRA_STUFF, s);
intent.putExtras(basket);
setResult(RESULT_OK, intent);
finish();
}
}
The second activity is fired correctly, and receive the data from the main one, but once the data is sent back the onActivityResult is not fired!!
How can I solve it? thanks

Remove the finish() call that comes after startActivityForResult(). You prevent the oncoming activity to give a result back, because you remove your MainActivity with finish() from the back task.

Dont call finish() after startActivityForResult otherwise that instance of MainActivity that started the second one will be destroyed

Related

Value of Toast to TextView of second activity

This is my MainActivity.java and I want the results in a text view of another activity? How can I achieve it? Can you Show me with an example please.
public class MainActivity extends AppCompatActivity {
private Button scan_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scan_btn=(Button)findViewById(R.id.btnQr);
final Activity activity =this;
scan_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator intentIntegrator = new IntentIntegrator(activity);
intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
intentIntegrator.setPrompt("Scan");
intentIntegrator.setCameraId(0);
intentIntegrator.setBeepEnabled(false);
intentIntegrator.setBarcodeImageEnabled(false);
intentIntegrator.initiateScan();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null){
if (result.getContents()==null){
Toast.makeText(this,"You cancelled scanning",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this,result.getContents(),Toast.LENGTH_LONG).show();
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
This is my Second Activity. Where I want to show the result.
public class DetailActivity extends AppCompatActivity {
private TextView qrResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
qrResult= findViewById(R.id.qrResult);
}
}
If you want I can post my Layout file as well. Thankyou.
You need to create a new Intent object, and add it extra data with intent.putextra(). This method can take a String object as an argument. You need to specify a unique key for that string.Then start the new activity. For example
Intent i = new Intent(context, nextactivity.class)
i.putextra(“stringKey”,yourSstring)
startActivity(i)
Then, in the second activity, you need to get the intent that started that activity (with getIntent), you can use it as early as onCreate.
The getIntent function returns the intent object that started the new activity.
When you have the new intent, you can get the extra string you passed from the old activity, with intent.getStringExtra(“stringKey”)
This allows you to pass simple data between activities. Make sure to use the same key.
You can put data into the intent from your main acivity and the get the intend from the second activity for the data.
For example:
In your MainActivity.class
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("result", "Your result text here");
startActivity(intent);
In Your DetailsActivity.class:
Intent intent = getIntent();
String result = intent.getStringExtra("result");
qrResult.setText(result);
You can even send any type of object through intent. Please google it for further information.

onActivityResult return data from fragment to activity

I Have an activity A that opens an activity B using startActivityForResult.
Now in activity B it's an activity fragment holder as well it contains an ActionBar with menu items.
Now whenever I press action bar button in activity B it should return data from selected fragment of an activity B not to its holder instead it should return data to activity A because it's the one who did the launch.
So it's basically passing data fragment (inside activity B) to activity B then to Activity A.
I am trying hopelessly to find a way to solve it. Is there any possible way to do it?
Disclaimer there are many ways, this is the one I prefer, not the best ever and not the perfect one, I just like this.
The easiest way, in my opinion, is to pass the data from Fragment inside B to ActivityB, then from ActivityB to ActivityA.
Step 1 to pass data from Fragment to container activity you have many ways; the one I usually use is to use an Interface:
Create interface for ActivityB
public interface IActivityB {
void setDataAAndFinish(whateverType data);
}
Implement interface in your activityB
public class InterventoActivity extends AppCompatActivity implements IInterventoActivity {
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private Bundle dataA = null;
#Override
public void setDataAAndFinish(whateverType data) {
dataA = data;
Intent intent = new Intent();
intent.putExtra("data", data)
setResult(RESULT_OK, intent);
finish();
}
}
Set activityA to request and accept return from ActivityB
first, start activityB for result and not normally
Intent i = new Intent(this, ActivityB.class);
startActivityForResult(i, 1);
Then read result
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
whateverType data = data.getStringExtra("data");
}
}
}
Now from fragment
((IActivityB)getActivity()).setDataAAndFinish(myDatas);
You need to declare a function in your ActivityB like the following.
public void sendDataBackToActivityA(String dataToBePassedToActivityA) {
Intent intent = new Intent();
intent.putExtra("data", dataToBePassedToActivityA);
setResult(RESULT_OK, intent);
finish();
}
Now from the Fragment that you launched from ActivityB, just call the method on some action in your Fragment that was launched from ActivityB. So the pseudo implementation of the process in your Fragment should look like the following. Declare this function in your Fragment and invoke the function on some action in your Fragment.
public void sendDataToActivityAFromFragment(String dataToBePassed) {
((ActivityB)getActivity()).sendDataBackToActivityA(dataToBePassed);
}
This will serve your purpose I hope.
You can declare static variables in your A activity and set it from the B activity
Or you can make static class and set variables values from B Activity and get it in A activity
Or you can send the menu value from Activity B to A while you exit Activity B and start activity A by using bundle
this is how you set the data to be passed to activity A in activity B
val resultIntent = Intent()
resultIntent.putExtra(DATA, "closed")
setResult(Activity.RESULT_OK, resultIntent)
finish()
this is how you get data in activity A
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == FILE_UPLOAD_CODE) {
when (resultCode) {
Activity.RESULT_OK -> {
// data here is obtained data of the method paramater
}}}}
In your Activity A.Move from activity A to b like this:-
int YOUR_CODE=101; // it can be whatever you like
Intent i = new Intent(getActivity(), B.class);
startActivityForResult(i,YOUR_CODE);
In your Activity B in its fragment
Intent resultIntent = new Intent();
resultIntent.putExtra("NAME OF THE PARAMETER", valueOfParameter);
...
setResult(Activity.RESULT_OK, resultIntent);
finish();
And in your Activity A's onActivityResult() function do this:-
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (resultCode==YOUR_CODE)
{
String value = (String) data.getExtras().getString("NAME OF THE PARAMETER"); //get Data here
}
}
}
In kotlin: -
In class A
startActivityForResult(Intent(context, B::class.java), 143)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == 143) {
if (data!!.extras.get("check").equals("0")) {
childpager.currentItem = 0
}
}
}
In Class B
val intent = Intent()
intent.putExtra("check", "0")
setResult(Activity.RESULT_OK, intent)

Passing the selected object to an Another Activity

I have a news activity in which there is a list of news.I want a user to select a news from the list and direct him to the news_details page where I give the details about the selected news, however when the user selects the news, program goes quickly to news_details and comes back again to the news.
News:
public void Listen() {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() { // ana sayfada herhangi bir item seçildiğinde
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
i.putExtra("title", selectedNews.getTitle());
i.putExtra("date", selectedNews.getNewsDate().toString());
i.putExtra("image_id", selectedNews.getImageId());
i.putExtra("text", selectedNews.getText());
setResult(RESULT_OK, i);
startActivity(i);
}
});
}
News_Details:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news__details);
Intent i = new Intent(this,MainActivity.class);
startActivityForResult(i, GET_NEWS);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GET_NEWS) { // Check which request we're responding to
if (resultCode == RESULT_OK) { // Make sure the request was successful
title.setText(data.getStringExtra("title"));
date.setText(data.getStringExtra("date"));
news_img.setImageResource(data.getIntExtra("image_id", 0));
news_text.setText(data.getStringExtra("text"));
}
}
}
}
First of all, remove this line:
setResult(RESULT_OK, i);
Also, remove this line from newsdetails activity:
startActivityForResult(i, GET_NEWS);
Make changes as below:
public void Listen() {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
i.putExtra("title", selectedNews.getTitle());
i.putExtra("date", selectedNews.getNewsDate().toString());
i.putExtra("image_id", selectedNews.getImageId());
i.putExtra("text", selectedNews.getText());
startActivity(i);
}
});
}
Then, in your news details activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news__details);
Intent i = getIntent();
String title = i.getStringExtra("title");
String date = i.getStringExtra("date");
int imageId = i.getIntExtra("image_id");
String text = i.getStringExtra("text");
}
OnActivityResult method is not required so simply remove it.
FYI:
startActivity and startActivityForResult both of them start new activities , but startActivityForResult as the name suggests that you are expecting a result from the activity you are starting. And this result shall be obtained in onActivityResult method.
Say for example, you want to start Activity2 from Activity1, and you want to pass some data back to Activity1 while finishing Activity2. You simply set the Result in Activity2 using setResult() method. and while Activity1 resumes again, its onActivityResult() will be invoked, you will override onActivityResult() in Activity1 to receive the Result set by Activity2.
Hope you are now clear on this.
Remove these lines
setResult(RESULT_OK, i);
Intent i = new Intent(this,MainActivity.class);
startActivityForResult(i, GET_NEWS);
Use google Gson for serializing the object.
NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
String strNews = new Gson().toJson(selectedNews);
Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
i.putExtra("news", strNews);
startActivity(i);
On other hand News details onCreate() do this
Bundle bundle = getIntent().getExtras();
String newsStr = bundle.getString("news");
Gson gson = new Gson();
Type type = new TypeToken<NewsItem>() {
}.getType();
NewsItem selectedNews = gson.fromJson(newsStr, type);
to send string value
NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
Intent i=new Intent(MainActivity.this, News_Details_Activity.class);
i.putExtra("title", selectedNews.getTitle());
i.putExtra("date", selectedNews.getNewsDate().toString());
i.putExtra("image_id", selectedNews.getImageId());
i.putExtra("text", selectedNews.getText());
startActivity(i);
to recieve in News_Details_Activity
Intent i = getIntent();
title = i.getStringExtra("title");
date= i.getStringExtra("date");
text= i.getStringExtra("text");
you can do it using Serializable by following way
public class News implements Serializable{
String title;
String desc;
String time,imageUrl;
}
Then News List activity
Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
i.putExtra("news",newsObject);
and get it onCreate of NewsDetail
News news=(News) getIntent().getExtras().getSerializable("news");
and user it like title.setText(news.getTitle());
make News class that implements Serialazable
Create new Object of News class , and put into intent as putSerialazable();
in your second activity just getIntent().getSerialazable("key") and set your data to views.

Can I pass an Intent extra on finish()?

I'm wondering, is it possible to send information to the activity that I return to after calling finish()?
For example, I have an Activity SendMessageActivity.class which allows the user to post a message to their feed. Once that message has been saved to the server, I call finish(). Should I instead just start my MainActivity.class with a new Intent? Or is it better for life cycle development to just finish SendMessageActivity.class?
I don't see the point of starting a new activity since closing the current one will always bring you back to MainActivity.class. How can I just send a String extra after finishing the current Activity?
Use onActivityResult.
This might help you to understand onActivityResult.
By using startActivityForResult(Intent intent, int requestCode) you can start another Activity and then receive a result from that Activity in the onActivityResult() method.So onActivityResult() is from where you start the another Activity.
onActivityResult(int requestCode, int resultCode, Intent data) check the params here. request code is there to filter from where you got the result. so you can identify different data using their requestCodes!
Example
public class MainActivity extends Activity {
// Use a unique request code for each use case
private static final int REQUEST_CODE_EXAMPLE = 0x9988;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an Intent to start AnotherActivity
final Intent intent = new Intent(this, AnotherActivity.class);
// Start AnotherActivity with the request code
startActivityForResult(intent, REQUEST_CODE_EXAMPLE);
}
//-------- When a result is returned from another Activity onActivityResult is called.--------- //
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// First we need to check if the requestCode matches the one we used.
if(requestCode == REQUEST_CODE_EXAMPLE) {
// The resultCode is set by the AnotherActivity
// By convention RESULT_OK means that what ever
// AnotherActivity did was successful
if(resultCode == Activity.RESULT_OK) {
// Get the result from the returned Intent
final String result = data.getStringExtra(AnotherActivity.EXTRA_DATA);
// Use the data - in this case, display it in a Toast.
Toast.makeText(this, "Result: " + result, Toast.LENGTH_LONG).show();
} else {
// AnotherActivity was not successful. No data to retrieve.
}
}
}
}
AnotherActivity <- This the the one we use to send data to MainActivity
public class AnotherActivity extends Activity {
// Constant used to identify data sent between Activities.
public static final String EXTRA_DATA = "EXTRA_DATA";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
final View button = findViewById(R.id.button);
// When this button is clicked we want to return a result
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create a new Intent as container for the result
final Intent data = new Intent();
// Add the required data to be returned to the MainActivity
data.putExtra(EXTRA_DATA, "Some interesting data!");
// Set the resultCode to Activity.RESULT_OK to
// indicate a success and attach the Intent
// which contains our result data
setResult(Activity.RESULT_OK, data);
// With finish() we close the AnotherActivity to
// return to MainActivity
finish();
}
});
}
#Override
public void onBackPressed() {
// When the user hits the back button set the resultCode
// to Activity.RESULT_CANCELED to indicate a failure
setResult(Activity.RESULT_CANCELED);
super.onBackPressed();
}
}
Note : Now check in MainActivity you startActivityForResult there you specify a REQUEST_CODE. Let's say you want to call three different Activities to get results.. so there are three startActivityForResult calls with three different REQUEST_CODE's. REQUEST_CODE is nothing but a unique key you specify in your activity to uniquely identify your startActivityForResult calls.
Once you receive data from those Activities you can check what is the REQUEST_CODE, then you know ah ha this result is from this Activity.
It's like you send mails to your lovers with a colorful covers and ask them to reply in the same covers. Then if you get a letter back from them, you know who sent that one for you. awww ;)
You can set result of an activity, which allow you to data into an initent.
In your first activity, call the new one with startActivityForResult() and retrieve data in method onActivityResult. Everything is in documentation.
try this:
in First Activity:
Intent first = new Intent(ActivityA,this, ActivityB.class);
startActivityForResult(first, 1);
Now in Second activity: set Result during finish()
Intent intent = new Intent();
intent.putExtra("result",result); //pass intent extra here
setResult(RESULT_OK,intent);
finish();
First activity Catch the result;
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 1
if(requestCode==1)
{
String message=data.getStringExtra("result");
//get the result
}
}
If you call finish() to avoid that the user go back to SendMessageActivity.class, you can set this flags to your intent:
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
This will open the MainActivity and remove the SendMessageActivity from the activities stack.

How to start an activity which calls a method from a different class?

I have an activity which transfer a string datatype to another activity which then uses that string and calls a method from another class which returns a string. I want to use that method to display the string in the current activity.
So visually it goes (activity 1) -- string--> (activity 2). Activity 2 uses that string to call a method in a different java class which returns a type string which i want to display on the screen along with a few buttons.
So some pseudo code:
say The method in a different java class is:
public static String getStringexample(String n) {
return "hello" + " " + n;
}
and my activity class is:
public class manage extends Activity {
protected void onCreate(bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContainerView(R.layout.activity_manage);
Intent intent = getIntent();
String example = intent.getExtras().getString("intentid");
i'm lost after this..not sure how to use what i got from the intent to display it on the screen in java code.
Information between activities is passed in 'extras'. That is just a collection of string keys and values.
Both sides need to use the same keys, so define static final strings with they keys that your destination activity expects.
Then read the values from the extras using the key and go from there:
public class DestinationActivity extends Activity {
// let your callers know how to pass you the information you need
public static final String EXTRA_N = "n";
private TextView resultText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_destination);
resultText = (TextView) findViewById(R.id.resultText);
// get the information you was passed
Intent intent = getIntent();
String n = intent.getStringExtra(EXTRA_N);
// do your transformation using the other class
String example = DifferentClass.getStringexample(n);
// display the transformed string
resultText.setText(example);
}
// ...
}
The calling activity sends the information like this:
Intent intent = new Intent(this, DestinationActivity.class);
intent.putExtra(DestinationActivity.EXTRA_N, "foo");
startActivity(intent);
Good luck
You can start activity as
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
Then return to first activity from second activity
Intent returnIntent = new Intent();
returnIntent.putExtra("result",yourdata);
setResult(RESULT_OK,returnIntent);
finish();
In your first activity you will get result by using below code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}

Categories

Resources