Home > Mobile >  Pass an object from Activity to Main activity
Pass an object from Activity to Main activity

Time:09-26

I want to pass an object from Activity to Main activity, i search for this but i can't use startActivityForResul because it is deprecated. So i use like this, but it tells can't cast from Serializable to Contact object. How can i fix this

Main activity:

ActivityResultLauncher<Intent> intentLauch = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if(result.getResultCode()== Activity.RESULT_OK){
                    Contact contact = getIntent().getSerializableExtra("data");//error here
                }
            }
    );
    binding.bntAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this,AddActivity.class);
            intentLauch.launch(intent);

        }
    });

Activity:

private void setUpBnt()
{
    binding.bntSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String name = binding.edName.getText().toString();
            String phone = binding.edPhone.getText().toString();
            String mail = binding.edMail.getText().toString();

            Contact contact = new Contact(name,phone,mail,"");
            Intent intent = new Intent(AddActivity.this,MainActivity.class);
            intent.putExtra("data",contact);
            setResult(Activity.RESULT_OK,intent);
            finish();
        }
    });
}

CodePudding user response:

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source code of. you can easily share Gson objects via intent.

In your build.Gradle, add this to your dependencies

  implementation 'com.google.code.gson:gson:2.8.8'

In your Activity, convert the object to json-string:

Gson gson = new Gson();
String myJson = gson.toJson(vp);
intent.putExtra("myjson", myjson);

In your receiving Activity, convert the json-string back to the original object:

  Gson gson = new Gson();
YourObject ob = gson.fromJson(getIntent().getStringExtra("myjson"), YourObject.class);

For Kotlin it's quite the same

Pass the data

val gson = Gson()
val intent = Intent(this, YourActivity::class.java)
intent.putExtra("identifier", gson.toJson(your_object))
startActivity(intent)

Receive the data

val gson = Gson()
val yourObject = gson.fromJson<YourObject>(intent.getStringExtra("identifier"), YourObject::class.java)
  • Related