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条回答
ゆ 、 Hurt°
2楼-- · 2020-01-22 10:58

You can send data between activities using intent object. Consider you have two activities namely FirstActivity and SecondActivity.

Inside FirstActivity:

Using Intent:

i = new Intent(FirstActivity.this,SecondActivity.class);
i.putExtra("key", value);
startActivity(i)

Inside SecondActivity

Bundle bundle= getIntent().getExtras();

Now you can use different bundle class methods to get values passed from FirstActivity by Key.

E.g. bundle.getString("key"),bundle.getDouble("key") ,bundle.getInt("key") etc.

查看更多
我命由我不由天
3楼-- · 2020-01-22 10:59

You can use Intent

Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
mIntent.putExtra("data", data);
startActivity(mIntent);

Another way could be using singleton pattern also:

public class DataHolder {

 private static DataHolder dataHolder;
 private List<Model> dataList;

 public void setDataList(List<Model>dataList) {
    this.dataList = dataList;
 }

 public List<Model> getDataList() {
    return dataList;
 }

 public synchronized static DataHolder getInstance() {
    if (dataHolder == null) {
       dataHolder = new DataHolder();
    }
    return dataHolder;
 }
}

From your FirstActivity

private List<Model> dataList = new ArrayList<>();
DataHolder.getInstance().setDataList(dataList);

On SecondActivity

private List<Model> dataList = DataHolder.getInstance().getDataList();
查看更多
看我几分像从前
4楼-- · 2020-01-22 10:59

Charlie Collins gave me a perfect answer using the Application.class. I was not aware that we could subclass it that easily. Here is a simplified example using a custom application class.

AndroidManifest.xml

Give the android:name attribute to use your own application class.

...
<application android:name="MyApplication"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
....

MyApplication.java

Use this as a global reference holder. It works fine within a same process.

public class MyApplication extends Application {
    private MainActivity mainActivity;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public void setMainActivity(MainActivity activity) { this.mainActivity=activity; }
    public MainActivity getMainActivity() { return mainActivity; }
}

MainActivity.java

Set the global "singleton" reference to the application instance.

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ((MyApplication)getApplication()).setMainActivity(this);
    }
    ...

}

MyPreferences.java

A simple example where I use a main activity from another activity instance.

public class MyPreferences extends PreferenceActivity
            implements SharedPreferences.OnSharedPreferenceChangeListener {
    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        PreferenceManager.getDefaultSharedPreferences(this)
            .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        if (!key.equals("autostart")) {
            ((MyApplication)getApplication()).getMainActivity().refreshUI();
        }
    }
}
查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-01-22 11:01

The standard approach.

Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
Bundle bundle = new Bundle();
bundle.putString(“stuff”, getrec);
i.putExtras(bundle);
startActivity(i);

Now in your second activity retrieve your data from the bundle:

Get the bundle

Bundle bundle = getIntent().getExtras();

Extract the data…

String stuff = bundle.getString(“stuff”); 
查看更多
该账号已被封号
6楼-- · 2020-01-22 11:01

I recently released Vapor API, a jQuery flavored Android framework that makes all sorts of tasks like this simpler. As mentioned, SharedPreferences is one way you could do this.

VaporSharedPreferences is implemented as Singleton so that is one option, and in Vapor API it has a heavily overloaded .put(...) method so you don't have to explicitly worry about the datatype you are committing - providing it is supported. It is also fluent, so you can chain calls:

$.prefs(...).put("val1", 123).put("val2", "Hello World!").put("something", 3.34);

It also optionally autosaves changes, and unifies the reading and writing process under-the-hood so you don't need to explicitly retrieve an Editor like you do in standard Android.

Alternatively you could use an Intent. In Vapor API you can also use the chainable overloaded .put(...) method on a VaporIntent:

$.Intent().put("data", "myData").put("more", 568)...

And pass it as an extra, as mentioned in the other answers. You can retrieve extras from your Activity, and furthermore if you are using VaporActivity this is done for you automatically so you can use:

this.extras()

To retrieve them at the other end in the Activity you switch to.

Hope that is of interest to some :)

查看更多
再贱就再见
7楼-- · 2020-01-22 11:03

You can try Shared Preference, it may be a good alternative for sharing data between the activities

To save session id -

SharedPreferences pref = myContexy.getSharedPreferences("Session 
Data",MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
edit.putInt("Session ID", session_id);
edit.commit();

To get them -

SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
session_id = pref.getInt("Session ID", 0);
查看更多
登录 后发表回答