Submit Post - Article - Ask a Question - Ask an Interview Question - Submit Useful Links

How to pass an object from one activity to another on Android

How can i pass an object to intent using android studio 3.0.1

By      08-Nov-2023    2

Solutions


Nawab

you can achive this by using Gson  if you do not have Gson in your project just add the  below line in you Build.gradle(Module.app)

compile 'com.google.code.gson:gson:2.8.1'

after adding this build you App and then use as below

Gson gson=new Gson ();
String myJson=gson.toJson(YourClassModel);
Intent intent = new Intent(MainActivity.this, yourRedirctiveActivity.class);
intent.putExtra("MyCustomObj", myJson);
startActivity(intent);

Now go to the landing Activity and use below code to get your object

Gson gson= new Gson();
if (getIntent().getExtras()!=null){
    
yourClassobject=new yourClassobject();
    yourClassobject= gson.fromJson(getIntent().getStringExtra("MyCustomObj"),yourClassobject.class);
}

hope so it will resolve yours problem

 

Your Answer

21
Submit Post - Article - Ask a Question - Ask an Interview Question - Submit Useful Links