How do I pass data between Activities in Android a

2020-01-22 10:15发布

I have a scenario where, after logging in through a login page, there will be a sign-out button on each activity.

On clicking sign-out, I will be passing the session id of the signed in user to sign-out. Can anyone guide me on how to keep session id available to all activities?

Any alternative to this case

30条回答
我只想做你的唯一
2楼-- · 2020-01-22 10:44

If you want to tranfer bitmap between Activites/Fragments


Activity

To pass a bitmap between Activites

Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);

And in the Activity class

Bitmap bitmap = getIntent().getParcelableExtra("bitmap");

Fragment

To pass a bitmap between Fragments

SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);

To receive inside the SecondFragment

Bitmap bitmap = getArguments().getParcelable("bitmap");

Transfering Large Bitmaps

If you are getting failed binder transaction, this means you are exceeding the binder transaction buffer by transferring large element from one activity to another activity.

So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity, like this

In the FirstActivity

Intent intent = new Intent(this, SecondActivity.class);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray(); 
intent.putExtra("bitmapbytes",bytes);

And in the SecondActivity

byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
查看更多
3楼-- · 2020-01-22 10:44

Supplemental Answer: Naming Conventions for the Key String

The actual process of passing data has already been answered, however most of the answers use hard coded strings for the key name in the Intent. This is usually fine when used only within your app. However, the documentation recommends using the EXTRA_* constants for standardized data types.

Example 1: Using Intent.EXTRA_* keys

First activity

Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, "my text");
startActivity(intent);

Second activity:

Intent intent = getIntent();
String myText = intent.getExtras().getString(Intent.EXTRA_TEXT);

Example 2: Defining your own static final key

If one of the Intent.EXTRA_* Strings does not suit your needs, you can define your own at the beginning of the first activity.

static final String EXTRA_STUFF = "com.myPackageName.EXTRA_STUFF";

Including the package name is just a convention if you are only using the key in your own app. But it is a necessity to avoid naming conflicts if you are creating some sort of service that other apps can call with an Intent.

First activity:

Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(EXTRA_STUFF, "my text");
startActivity(intent);

Second activity:

Intent intent = getIntent();
String myText = intent.getExtras().getString(FirstActivity.EXTRA_STUFF);

Example 3: Using a String resource key

Although not mentioned in the documentation, this answer recommends using a String resource to avoid dependencies between activities.

strings.xml

 <string name="EXTRA_STUFF">com.myPackageName.MY_NAME</string>

First activity

Intent intent = new Intent(getActivity(), SecondActivity.class);
intent.putExtra(getString(R.string.EXTRA_STUFF), "my text");
startActivity(intent);

Second activity

Intent intent = getIntent();
String myText = intent.getExtras().getString(getString(R.string.EXTRA_STUFF));
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-01-22 10:44

First Activity:

Intent intent = new Intent(getApplicationContext(), ClassName.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);

Second Activity:

String str= getIntent().getStringExtra("Variable name which you sent as an extra");
查看更多
狗以群分
5楼-- · 2020-01-22 10:45

Updated Note that I had mentioned the use of SharedPreference. It has a simple API and is accessible across an application's activities. But this is a clumsy solution, and is a security risk if you pass around sensitive data. It's best to use intents. It has an extensive list of overloaded methods that can be used to better transfer many different data types between activities. Have a look at intent.putExtra. This link presents the use of putExtra quite well.

In passing data between activities, my preferred approach is to create a static method for the relevant activity that includes the required parameters launch the intent. Which then provides easily setup and retrieve parameters. So it can look like this

public class MyActivity extends Activity {
    public static final String ARG_PARAM1 = "arg_param1";
...
public static getIntent(Activity from, String param1, Long param2...) {
    Intent intent = new Intent(from, MyActivity.class);
        intent.putExtra(ARG_PARAM1, param1);
        intent.putExtra(ARG_PARAM2, param2);
        return intent;
}

....
// Use it like this.
startActivity(MyActvitiy.getIntent(FromActivity.this, varA, varB, ...));
...

Then you can create an intent for the intended activity and ensure you have all the parameters. You can adapt for fragments to. A simple example above, but you get the idea.

查看更多
男人必须洒脱
6楼-- · 2020-01-22 10:45

The passing of data between activities is mainly by means of an intent object.

First you have to attach the data to the intent object with the use of the Bundle class. Then call the activity using either startActivity() or startActivityForResult() methods.

You can find more information about it, with an example from the blog post Passing data to an Activity.

查看更多
我想做一个坏孩纸
7楼-- · 2020-01-22 10:46

You can use SharedPreferences...

  1. Logging. Time store session id in SharedPreferences

    SharedPreferences preferences = getSharedPreferences("session",getApplicationContext().MODE_PRIVATE);
    Editor editor = preferences.edit();
    editor.putString("sessionId", sessionId);
    editor.commit();
    
  2. Signout. Time fetch session id in sharedpreferences

    SharedPreferences preferences = getSharedPreferences("session", getApplicationContext().MODE_PRIVATE);
    String sessionId = preferences.getString("sessionId", null);
    

If you don't have the required session id, then remove sharedpreferences:

SharedPreferences settings = context.getSharedPreferences("session", Context.MODE_PRIVATE);
settings.edit().clear().commit();

That is very useful, because one time you save the value and then retrieve anywhere of activity.

查看更多
登录 后发表回答