How to pass data from an activity to a fragment on android - android

I've an activity named ‘Home’; I’m redirected to this activity after a login. This activity implements two fragments (Header & footer) in this way.
View header = inflater.inflate(R.layout.fragment_header_fragement, null);
View footer = inflater.inflate(R.layout.fragment_footer, null);
mDrawerListView.addHeaderView(header);
mDrawerListView.addFooterView(footer);
And I want to display mainly into the header fragment implemented into the 'Home' activity some data transferred from the logging activity. The problem that I’ve searched a little bit, I’ve found that we can just add or replace a fragment in the main activity and not in another fragment. I'm tried to fund a solutions but not yet. This is my code :
#Override
protected void onPostExecute(final String res) {
//LoginTask = null;
//showProgress(false);
try {
jObj = new JSONObject(res);
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (jObj.getString("code").equals("1")) {
infos = new Bundle();
infos.putString("ID",jObj.getString("ID"));
infos.putString("Name",jObj.getString("display_name"));
infos.putString("ImgUrl","http://unchained-network.com/uploads/profilpics/53f5c570b6ac2.png");
android.support.v4.app.FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
HeaderFragement hf = new HeaderFragement();
//Charger les infos dans l'activité
hf.setArguments(infos);
tr.add(R.id.frgmnt,hf);
tr.commit();
Intent myIntent = new Intent(getActivity(), HomesActivity.class);
//Lançer l'activité
startActivityForResult(myIntent, 0);
} else {
//password.setError(getString(R.string.error_incorrect_password));
//password.requestFocus();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Error !");
builder.setMessage("The information entered is incorrect.\nPlease try again!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
And this is how i extract the data into the fragment
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
name = (TextView) getView().findViewById(R.id.nameH);
img = (ImageView) getView().findViewById(R.id.imageViewHeader);
Bundle infos = getArguments();
name.setText(infos.getString("Name"));
img.setImageBitmap(getBitmapFromURL(infos.getString("ImgUrl")));
}
So any solution please. Thanks

Why don't you just pass data via intents? You have two activities Login and Home.
Intent myIntent = new Intent(getActivity(), HomesActivity.class);
//Lançer l'activité
startActivityForResult(myIntent, 0);
In the above code, you could simply add an extra information like this
myIntent.putExtra("name", "value");
And then you could retrieve this in Home Activity
String extra = i.getStringExtra("name");
And then pass this extra to your header fragment.

There isn't anything wrong with your code to pass a variable to a Fragment. I've just copied your code and it works fine.
Activity:
Bundle infos = new Bundle();
infos.putString("ID", "1");
infos.putString("Name", "Gonzo");
FragmentMain frag = new FragmentMain();
frag.setArguments(infos);
Fragment:
Bundle infos = getArguments();
Log.i(getTag(), infos.getString("Name"));
I'd suggest you put some logging into the onPostExecute, or step through in debug mode. Ensure your json is returning what you expect it to.
As a general suggestion, infos.getString accepts two params, the second is a default value which may be useful. Also avoid using a hard coded key, like "Name" instead use a public static string and reference this.
Good luck.

Related

Start Activity from RecyclerView.Adapter with bundled Object

I'm using RecyclerView to populate CardViews with my object "Income". Now I need one of the buttons in CardView to start new Activity and send that object to it.
Here's part of my button's onClickListener in Adapter:
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editAt(income);
}
});
public void editAt(Income income){
Intent i = new Intent(context,IncomeAddActivity.class);
Bundle bundle = new Bundle();
// here I want to send that "income" object
i.putExtras(bundle);
startActivity(i);
}
Is there any easy method to do this, or my approach is totally wrong?
You need to make your class Income implements the interface Serializable. Then you can do this:
Bundle bundle = new Bundle();
bundle.putSerializable("object", income);
intent.putExtras(bundle);
startActivity(i);
You can also use Shared Preferences to store and get some data
SharedPreferences.Editor ed = mPrefs.edit();
ed.putInt("view_mode", mCurViewMode);
ed.commit();

Can't retrieve intent extras

I have a main activity with a recyclerview that contains images inside imageviews. When you click on an image, a detail activity is launched.
I need to pass 2 objects to an intent and retrieve them in the detail activity, but for some reason I can't do it. When I use a debugger, I can see that both objects are saved in the intent extras.
However, when I fetch them on the other side, I can't find my arraylist extra.
Can you help me to figure out why?
This is my code:
holder.mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mActivity.isTwoPaneMode()) {
Bundle arguments = new Bundle();
arguments.putParcelable(MovieListActivity.MOVIE,movie);
arguments.putStringArrayList("TRAILERS", (ArrayList)movie.getTrailerList());
MovieDetailFragment fragment = new MovieDetailFragment();
fragment.setArguments(arguments);
mActivity.getSupportFragmentManager().beginTransaction()
.replace(R.id.movie_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MovieDetailActivity.class);
intent.putExtra(MovieListActivity.MOVIE, movie);
intent.putStringArrayListExtra("TRAILERS", (ArrayList)movie.getTrailerList());
context.startActivity(intent);
}
}
});
On the other activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_detail);
if (savedInstanceState == null) {
Intent intent = getIntent();
ArrayList<String> trailers = intent.getStringArrayListExtra("TRAILERS");
Movie movie = intent.getParcelableExtra(MovieListActivity.MOVIE);
Bundle arguments = new Bundle();
arguments.putParcelable(MovieListActivity.MOVIE, movie);
arguments.putStringArrayList(MovieListActivity.MOVIE,
getIntent().getStringArrayListExtra("TRAILERS"));
MovieDetailFragment fragment = new MovieDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.movie_detail_container, fragment)
.commit();
}
}
My movie class implements parcelable correctly.
Take a look at the Android Intent docs here.
Specifically, the The name must include a package prefix, ... when using Intent#putStringArrayListExtra.
Try something like this:
intent.putStringArrayListExtra(PACKAGE_NAME + ".TRAILERS", (ArrayList)movie.getTrailerList());
where PACKAGE_NAME is equal to your application's package name.
Try fetching data from a Bundle instead of and Intent. This way you can know if data was actually passed to the activity because the Bundle will be null if nothing was passed. Also add the package name to the data String.
PACKAGE_NAME = getApplicationContext().getPackageName();
arguments.putStringArrayList(PACKAGE_NAME+"TRAILERS,(ArrayList)movie.getTrailerList());
Instead of doing:
Intent intent = getIntent();
ArrayList<String> trailers = intent.getStringArrayListExtra(PACKAGE_NAME+"TRAILERS");
do:
Bundle extras = getIntent().getExtras();
ArrayList<String> trailers;
if(extras!=null){
ArrayList<String> trailers = extras.getStringArrayList("TRAILERS");
}else{
Toast.makeToast(this, "No data was passed", Toast.LENGTH_LONG).show();
}
If the Toast shows up it means your data wasn't passed correctly.

Activity That has Several Extras from Other Activities?

I have an Activity that uses the following code to retrieve information from another activity:
Bundle extras = getIntent().getExtras();
if (extras != null) {
int tok = extras.getInt("Token");
tempToken += tok;
}
This is the Code inside the first other class that sends this information:
final Button mainMen = (Button) findViewById(R.id.toMainMenu);
mainMen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
Menu.class);
i.putExtra("Token", tok + teTok);
startActivity(i);
}
});
Now i have another Activity that also wants to sen information to the Main Activity like so:
maMenu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Campaign.this, Menu.class);
intent.putExtra("Token", player.tokens);
intent.putExtra("Round", player.round);
intent.putExtra("Rank", player.rank);
intent.putExtra("Score", player.score);
intent.putExtra("Sec", player.secondsTapped);
intent.putExtra("Min", player.minutesTapped);
intent.putExtra("Hour", player.hoursTapped);
intent.putExtra("Day", player.daysTapped);
intent.putExtra("LifeTap", player.tapsInLife);
intent.putExtra("SecTap", player.tapsPerSec);
intent.putExtra("TapRo", player.tapps);
startActivity(intent);
}
});
Now my question is, how do i handle these different extras from multiple Activities inside the one Main Activity?
Thank You for your time :)
There are two ways to solve your problem..
1)
You can pass one boolean value to or and int variable with some value.. And retrieve this in your new Activity and check with boolean value or int value and get correct data correspond to Activity.
2) You can save your all Data in Shared Preference. And get your all Data in any Activity.
you can send one boolean value that data is in first class or second class and in MainActivity check the value and get the correct data

Mark selected user as checked in FriendPicker (Facebook SDK for Android)

I've done the tutorials for the Facebook SDK for Android (Especially the "Show Friends"-tutorial).
How can I mark the selected users which i've selected before at the PickerActivity when i click on the "Show Friends"-button again?
I've looked at Facebook SDK's source code and it seems to me that PickerFragment does not give you possibility to reselect previously selected items. Since Facebook SDK is published under Apache License 2.0 and you have access to full source code I guess you could try to modify PickerFragment in such a way that it will have necessary methods.
You have to pass comma separated string with selected facebook user ids in the bundle to the FriendPickerFragment.
Bundle args = new Bundle();
args.putString("com.facebook.android.PickerFragment.Selection", "11111, 2222, 333, already selected facebook ids....");
friendPickerFragment = new FriendPickerFragment(args);
In PickerFragment's onActivityCreated() it will parse the selected ids shows as selected in list. You can see the following code in PickerFragment in FacebookSDK.
selectionStrategy.readSelectionFromBundle(savedInstanceState, SELECTION_BUNDLE_KEY);
Here is a solution which worked for me. I extend a standard FriendPickerFragment.
public class FriendPickerFragment2 extends FriendPickerFragment {
SelectionStrategy selectionStrategy;
String mPreSelectedIDs;
public FriendPickerFragment2(Bundle args)
{
super(args);
}
#Override
SelectionStrategy createSelectionStrategy() {
selectionStrategy = getMultiSelect() ? new MultiSelectionStrategy() : new SingleSelectionStrategy();
return selectionStrategy;
}
public void showInitialSelection()
{
Bundle bundle = new Bundle();
bundle.putString(this.MULTI_SELECT_BUNDLE_KEY, mPreSelectedIDs);
selectionStrategy.readSelectionFromBundle(bundle, this.MULTI_SELECT_BUNDLE_KEY);
adapter.notifyDataSetChanged();
}
public void setInitialSelection(String IDs)
{
mPreSelectedIDs = IDs;
}
}
I use FriendPickerFragment2 as a normal FriendPickerFragment. In OnCreate I do the following:
FragmentManager fm = getSupportFragmentManager();
if (savedInstanceState == null) {
final Bundle args = getIntent().getExtras();
friendPickerFragment = new FriendPickerFragment2(args);
friendPickerFragment.setInitialSelection(pickedUsersString());
fm.beginTransaction()
.add(R.id.friend_picker_fragment, friendPickerFragment)
.commit();
} else {
friendPickerFragment = (FriendPickerFragment2) fm.findFragmentById(R.id.friend_picker_fragment);
}
Here pickedUsersString is a coma separated string of IDs.
The last point is to add one row in the OnStart:
protected void onStart() {
super.onStart();
try {
friendPickerFragment.loadData(false);
friendPickerFragment.showInitialSelection();
} catch (Exception ex) {
onError(ex);
}
}
This solution worked for me.
Good news. In the current SDK version (3.6) the following feature was added:
Added setSelection methods on FriendPickerFragment to allow pre-selection of friends.
Added example use of setSelection API in Friend Picker Sample
FriendPickerFragment has this method:
/**
* Sets the list of friends for pre selection. These friends will be selected by default.
* #param userIds list of friends as ids
*/
public void setSelectionByIds(List<String> userIds) {
preSelectedFriendIds.addAll(userIds);
}
And this method:
public void setSelection(List<GraphUser> graphUsers) {
List<String> userIds = new ArrayList<String>();
for(GraphUser graphUser: graphUsers) {
userIds.add(graphUser.getId());
}
setSelectionByIds(userIds);
}
You should call one of these methods as soon as fragment instantiation:
friendPickerFragment = new FriendPickerFragment(args);
friendPickerFragment.setSelectionByIds(fbIDs);

getIntent.getExtras() does not return null but has no values.

Question is simple, I am not exactly new to Android but I cannot, for the life of me, retrieve the extras passed via an intent from Activity A to Activity B.
See Activity A: This is actually a ListFragment, that implements onListItemClick() to start another activity via an intent.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
Intent i = new Intent(getActivity(), ExpandedTweetView.class);
twitter4j.Status status = adapter.getItem(position);
Bundle extras = new Bundle();
extras.putString(KEY_TEXT, status.getText());
extras.putString(KEY_HANDLE, status.getUser().getScreenName());
extras.putString(KEY_NAME, status.getUser().getName());
extras.putString(KEY_TIMESTAMPS, status.getCreatedAt().toString());
extras.putLong(KEY_RETWEETS, status.getRetweetCount());
i.putExtra(KEY_EXTRAS, extras);
startActivity(i);
}
This part just works, I tested it usng Log.v(TAG, "status.getText()" to make sure that the error was not coming from the Adapter passing an empty item via getItem().
Here is the code on Activity B:
public class ExpandedTweetView extends Activity {
TextView text;
TextView name;
TextView handle;
TextView createdAt;
TextView retweets;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.expanded_list_item);
Bundle extras = getIntent().getExtras();
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
text = (TextView) findViewById(R.id.h_content);
name = (TextView) findViewById(R.id.h_name);
handle = (TextView) findViewById(R.id.h_handle);
createdAt = (TextView) findViewById(R.id.h_timestamp);
retweets = (TextView) findViewById(R.id.h_retweet_count);
if(extras != null) {
text.setText(extras.getString(TimelineFragment.KEY_TEXT));
name.setText(extras.getString(TimelineFragment.KEY_NAME));
handle.setText(extras.getString(TimelineFragment.KEY_HANDLE));
createdAt.setText(extras.getString(TimelineFragment.KEY_TIMESTAMPS));
retweets.setText(String.valueOf(extras.getLong(TimelineFragment.KEY_RETWEETS)));
}
}
As you can see, I believe I am using the right code to obtain the extras, using the same code on other applications worked. Not sure why, when the ExpandedTweetView is created via an intent, ALL of the textViews are empty. See: https://www.dropbox.com/s/pso6jbyn6rpks9n/empty_activity.png
What is even MORE strange is that I had initially tried checking to see if the bundle was null by calling this:
if (extras == null) {
Log.v(TAG, "Extras are empty :(");
}
But that line was never executed, meaning the bundle is not null. I also thought that maybe the keys being used to retrieve the individual Strings from the bundle were mismatching; however, in order to remedy that I decided to create constants that could be used on both sides. As you can see on the code, both the key to set the Extra and the Key to retrieve the Extra are the same.
Any ideas as to what the heck is going on?
Bundle extras = getIntent().getExtras();
if (extras != null) {
extras = extras.getBundle("KEY_EXTRAS");
String status = extras.getString("KEY_TEXT");
}
Try adding the extra variable to intent rather than in Bundle
Ex:
i.putExtra(KEY_1, a);
i.putExtra(KEY_2, b);
i.putExtra(KEY_3, c);
Then retrieve it from other activity from intent
Ex:
getIntent().getStringExtra(KEY_1) ;
In Activity A:
Intent i = new Intent(MainActivity.this, AnotherActivity.class);
Bundle b = new Bundle();
b.putString("thisc", "my name");
i.putExtra("bundle", b);
startActivity(i);
In Activity B:
**Bundle bun = getIntent().getBundleExtra("bundle");
if (bun.containsKey("thisc")) {
Log.i("TAG", bun.getString("thisc"));
} else {
Log.i("TAG", "no thisc");
}**
Check the first line of code in Activity B, that's the main difference actually!!
//put value
Intent inatent = new Intent(this,text.class);
inatent_logo.putExtra("message","hello");
startActivity(inatent);
//get vale
String msg = getIntent().getStringExtra("message").toString();
It's Difficult to maintain intent to Bundle and Bundle to Intent if number of data you want ti share from one Activity to Other Activity.
just Simply use Intent with PuExtra() with different argument.
you can pass number of data in intent like :
Sender's Side :
Create your Intent.
Intent My_Intent = new Intent(FromClass.this,ToClass.class);
Add your value which you want to share with other activity.
My_Intent.putExtra("VAR_A",a_value);
My_Intent.putExtra("VAR_B",b_value);
My_Intent.putExtra("VAR_C",c_value);
Call your Intent.
StartActivity(My_Intent);
Receiver's Side :
Intent My_Intent = getIntent();
First_Value=My_Intent.getStringExtra("VAR_A");
Sec_Value=My_Intent.getStringExtra("VAR_B");
Thred_Value=My_Intent.getStringExtra("VAR_C");
I Think its Easy for you to Handel your data from one Activity to other .

Categories

Resources