I want to start a service from my main activity and pass an object with Serializable. However when I get the object in the Service and I call a method, it is null and I don't know why. Here is my MainActivity class:
public class MainActivity extends AppCompatActivity implements View.OnClickListener, Serializable
{
private transient SetVocabulary setVocabulary;
private transient Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVocabulary = new SetVocabulary();
findViewById(R.id.imageDizionario).setOnClickListener(this);
findViewById(R.id.imageGruppi).setOnClickListener(this);
findViewById(R.id.imageImpara).setOnClickListener(this);
Intent intentService = new Intent(MainActivity.this, ServiceChiusuraApp.class);
intentService.putExtra(Constants.codiceMainActivity,this);
Bundle bundleService = new Bundle();
bundleService.putSerializable(Constants.codiceMainActivity,this);
intentService.putExtras(bundleService);
startService(intentService);
}
public SetVocabulary getSetVocabulary()
{
return setVocabulary;
}
@Override
public void onClick(View v)
{
startActivity(intent);
}
}
Here is my Service class:
public class ServiceChiusuraApp extends Service
{
MainActivity mainActivity;
@Override
public IBinder onBind(Intent intent)
{
mainActivity = (MainActivity) intent.getExtras().getSerializable(Constants.codiceMainActivity);
return null;
}
@Override
public void onTaskRemoved(Intent rootIntent)
{
super.onTaskRemoved(rootIntent);
SharedPreferences sharedPref = mainActivity.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet(Constants.codiceSetString,mainActivity.getSetVocabulary());
stopSelf();
}
}