Send data from Activity1 to a fragment of Activity2 by using Inent - android

I want to send a string from a recyclerView of Activity1 to a fragment of Activity2 using intent. for better understanding, here is the demonstration image
so I'm fetching the key from recyclerView like this
#Override
protected void populateViewHolder(EventsViewHolder viewHolder, EventDetails model, int position) {
viewHolder.setEventDate(model.getDate());
viewHolder.setEventIcon(getApplicationContext(),model.getIcon());
viewHolder.setEventTitle(model.getTitle());
viewHolder.setEventDescription(model.getDescription());
viewHolder.setEventTotalGuest(model.getTotal_guests());
String guest_key = getRef(position).getKey();
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent guestListIntent = new Intent(MainActivity.this, GuestListActivity.class);
startActivity(guestListIntent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
}
and now I want to send the guestKey by using intent from this activity to a fragment of GuestListActivity.class
I've tried Bundle but I can't send data.
TIA

First, send data from activity1 to activity2
Intent guestListIntent = new Intent(MainActivity.this, GuestListActivity.class);
guestListIntent.putExtra("guest_key",guest_key)
startActivity(guestListIntent);
Catch it in Activity 2
String guest_key = "";
Bundle bundle = getIntent().getExtras();
if(bundle != null){
guest_key = bundle.getString("guest_key","");
}
Now send to Fragment of Activity 2
Bundle bundle = new Bundle();
bundle.putString("guest_key", guest_key);
NewFragment newFragment = new NewFragment();
newFragment.setArguments(bundle);
Catch in Fragment onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String guest_key = getArguments().getString("guest_key","");
return inflater.inflate(R.layout.fragment_item_three, container, false);
}

send the data as u send from activity to activity and receive in fragment as getActivity().getIntent() and then do as you receive data in activity.

Here, any fragment of Activity2 is being created after onCreate() of this activity.
I will suggest you to use any of two approach to receive data in a Fragment of Activity2.
Approach 1:
Send data using Bundle with intent and receive it in Activity2 then set as Arguments while making transition of a fragment.
Bundle bundle = new Bundle();
bundle.putString("YOUR_KEY", "KEY_VALUE");
guestListIntent.putExtras(bundle);
startActivity(guestListIntent);
Receive this data in Activity2,
Bundle extras = getIntent().getExtras();
Set data while Fragment transition,
Fragment frag = new YOUR_FRAGMENT();
frag.setArguments(extras);
Receive data in Fragment,
String value= getArguments().getString("YOUR_KEY");
Approach 2:
Declare static variable. Assign value inside onClick then access and use this value from fragment class

You have to send the data to GuestListActivity and retrive the data in GuestListActivity. After that when you do the fragment tracation or add the fragment pass the data through bundle. Then you will be able to get the data in your desire fragment. For better understanding see the demonstration image.
send data to GuestListActivity
#Override
protected void populateViewHolder(EventsViewHolder viewHolder, EventDetails model, int position) {
// other code of view holder
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent guestListIntent = new Intent(MainActivity.this, GuestListActivity.class);
guestListIntent.putExtra("guest_key",guest_key)
startActivity(guestListIntent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
}
}
Retrieve the data in GuestListActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
String guest_key = "";
Bundle bundle = getIntent().getExtras();
if(bundle != null){
guest_key = bundle.getString("guest_key","");
}
}
Send the data to your fragment
Bundle bundle = new Bundle();
bundle.putString("guest_key", guest_key);
MyFragment myFragment = new MyFragment();
myFragment.setArguments(bundle);
Retrieve data in your fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String guest_key = getArguments().getString("guest_key","");
}

Related

Get Intent in Fragment

After seeing this question, it got me thinking. I can get a Intent in a Fragment by calling this inside onCreateView:
String Item = getActivity().getIntent().getExtras().getString("name");
the problem with this is that getActivity might return null, to counter that I can call:
if(getActivity() != null)
String Item = getActivity().getIntent().getExtras().getString("name");
}
this will work fine, but..
I was thinking of creating a static method in my Activity and then accessing the Intent in my fragment by calling that method, like this (In my Activity):
public class DemoActivity extends Activity{
static String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
//Getting the Intent from the previous Activity
name = getIntent().getStringExtra("name");
}
public static String Name(){
//returning the Intent
return name;
}
}
Then in my Fragment I can call this like this:
String name = DemoActivity.Name();
My Question:
Can I do it like this? Will it cause any issues and why?
Currently
It is working fine.
try like this:
Activity class:
Bundle bundle = new Bundle();
bundle.putString("your_key", "your_value");
your_fragment.setArguments(bundle);
Fragment class:
String your_variable = getArguments().getString("your_key");
Set in first activity fragment:
Bundle bundle = new Bundle();
bundle.putString("your_string_key", "your_value");
startActivity(new Intent(getActivity() your_second_activity.class).putExtra("bundle_key", bundle));
Get bundle value second activity:
fragment.setArguments(getIntent().getBundleExtra("bundle_key"));
In Second Activity Fragment:
getArguments().getString("your_string_key")

Android send ArrayList the object

I'm clumsy.
solution on my problem
origin activity
public void marcas(View view) {
ArrayList<Localizacion> object = new ArrayList<Localizacion>(localizaciones);
Intent intent = new Intent(getApplicationContext(), CompraVenta.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST", (Serializable) object);
intent.putExtra("BUNDLE", args);
startActivityForResult(intent, RESPUESTA_ACTIVIDAD);
}
destiny activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_compra_venta);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Localizacion> object = (ArrayList<Localizacion>) args.getSerializable("ARRAYLIST");
loc = object;
enlaceInterfaz();
}
in the class Localizacion i'm implement Parceable.
my mistake was to want to use the arrays like I use them in the java class and that's not how it works.
thanks for all
Make your class as Parceable, and then you will be able to pass the list of objects of that class to another Activity.
class Localizacion implements Parceable {
}
Now to send data to another Activity.
intent.putParcelableArrayListExtra("array",object);
In receiving side
loc = getIntent().getParcelableArrayExtra("array");

How to Determine which Fragment called the Activity

I have 2 Fragments that both pass an intent to an Activity (through an event listener). How can the Activity know which of these 2 fragments passed the intent? There's a method called getCallingActivity(), I need the equivalent for fragments.
I Attempted to determine which Fragment Called the Activity with the onAttachFragment() method, But it doesn't work:
public class DetailsActivity extends Activity {
static final String POSITION = "position";
private Movie movie;
private int position;
private static final String TAG = "app";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
}
#Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
Log.v(TAG, "fragment_src");
position = (int) getIntent().getExtras().get(POSITION);
if (fragment instanceof PopularFragment) {
movie = PopularFragment.movieList.get(position);
setData();
} else if (fragment instanceof TopRatedFragment) {
movie = TopRatedFragment.movieList.get(position);
setData();
}
}
public void setData() {
TextView original_title = (TextView) findViewById(R.id.original_title);
original_title.setText(movie.getOriginal_title());
...
}
}
You could send different int values with your intent for both fragment and check in your activity..or you could get your fragment by using
Fragment fragment = getFragmentManager().findFragmentByTag("yourtag");
Why don't you pass some parameters through the Intent itself
For first fragment-
Intent intent=new Intent(getActivity(),DetailsActivity.class);
intent.putExtra("fragName","PopularFragment");
startActivity(intent);
For Second Fragment-
Intent intent=new Intent(getActivity(),DetailsActivity.class);
intent.putExtra("fragName","TopRatedFragment");
startActivity(intent);
In your Activity
String fragName=getIntent().getStringExtra("fragName");
And then just check using if..else.

Using bundle for message passing in sliding tab fragments returns null

I am new at using fragments. This is how I am passing StringArrayList inside bundle in the onActivityCreated of first fragment in sliding tab
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
next_personal = (Button) getActivity().findViewById(R.id.personal_next);
next_personal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validate();
}
});
}
private void validate() {
isValid = FormValidator.validate(this, new SimpleErrorPopupCallback(getActivity().getApplicationContext(), true));
if (isValid) {
arrayList = new ArrayList<String>();
arrayList.add(memID.getText().toString());
arrayList.add(idNumber.getText().toString());
arrayList.add(firstName.getText().toString());
arrayList.add(secondName.getText().toString());
arrayList.add(lastName.getText().toString());
arrayList.add(secondLastName.getText().toString());
Bundle bundle = new Bundle();
bundle.putStringArrayList("personal",arrayList);
Log.d("bundle",": "+bundle.toString());
FragContactInfo frag = new FragContactInfo();
frag.setArguments(bundle);
((RegisterTabActivity) getActivity()).setCurrentItem(1, true);
}
}
And then I am trying to get the ArrayList in the third fragment of sliding tab as below:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null && bundle.containsKey("personal")) {
ArrayList<String> userId = bundle.getStringArrayList("personal");
}
else{
Toast.makeText(getActivity(),"Bundle is null",Toast.LENGTH_SHORT).show();
}
}
It keeps on returning null. Did the same inside onCreateView of both fragments, same result. What am I getting wrong here?
Using bundle did not help in parsing data between fragments (Somehow)
So I simply created method to set and get data in target fragment.
public void setPdata(JSONObject obj) {
this.personalJSON = obj;
}
public JSONObject getPdata() {
return personalJSON;
}
Then I called the set method to set json in sender fragment.
FragContactInfo frag = new FragContactInfo();
frag.setPdata(json);
And then access the json by simply calling get method.
array1 = getPdata().getJSONArray("args");
If anyone has a more productive solution, please do tell. Happy Coding.

How do I pass an integer to an instance of a class and use it to call the method of another class?

here's activity 1 which is a listview. when the user clicks on an item, I want the item clicked to launch an instance of a class and pass an int value to it, which will later be used in a switch.
#Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
switch(position){
case 0:
Intent g = new Intent(books.this, SpecificBook.class);
Bundle b = new Bundle();
b.putInt("dt", 0);
g.putExtras(b);
books.this.startActivity(g);
break;
case 1:
Intent ex = new Intent(books.this, SpecificBook.class);
Bundle b1 = new Bundle();
b1.putInt("dt", 1);
ex.putExtras(b1);
books.this.startActivity(ex);
break;
//etc.
here's activity 2, which is supposed to retrieve the int value and call the appropriate method from the database helper class.
public class SpecificBook extends Activity {
private DatabaseHelper Adapter;
Intent myLocalIntent = getIntent();
Bundle myBundle = myLocalIntent.getExtras();
int dt = myBundle.getInt("dt");
#SuppressWarnings("deprecation")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listy);
ListView lv = (ListView)findViewById(R.id.listview);
Adapter = new DatabaseHelper(this);
Adapter.open();
Cursor cursor = null;
switch(dt){
case 0:cursor = DatabaseHelper.getbook1Data(); break;
case 1:cursor = DatabaseHelper.getbook2Data(); break;
//etc.
}
startManagingCursor(cursor);
etc.
The database methods are queries.
Basically, I want each item in the book class listview to run it's own query based on the item selected and display the results.
I get a "source not found" and runtimeexception error. where am i going wrong? is there a better way to go about this?
I have already tried the "getter and setter" way to no avail. I've also tried the "putextra" method on the instance of the intent but that didn't work.
The earliest you can access an Intent is in onCreate():
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listy);
Intent myLocalIntent = getIntent();
Bundle myBundle = myLocalIntent.getExtras();
int dt = myBundle.getInt("dt");
You should check if the Intent or Bundle is null and if you only want the one item from your Intent you can use:
Intent myLocalIntent = getIntent();
if(myLocalIntent != null) {
int dt = myLocalIntent.getIntExtra("dt", -1); // -1 is an arbitrary default value
}
Lastly, you don't need to create a new Bundle to pass values in an Intent and it looks like you simply want to pass the position... So you can drastically shorten your onItemClick() method:
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent g = new Intent(books.this, SpecificBook.class);
g.putInt("dt", position);
books.this.startActivity(g);
}

Categories

Resources