Issue
An application about which I previously asked requires an ID for a particular activity, which is used to make a database query. When the activity starts I get this ID from an intent, thus:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counting);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
project_id = extras.getLong("project_id");
}
// ... the rest of the initialisation follows here
}
This activity (CountingActivity) in turn starts another via the user's interaction (EditProjectActivity) which has the CountingActivity as a parent so that navigation back via the home button works. In AndroidManifest.xml I have this:
<activity
android:name="myproject.EditProjectActivity"
android:label="@string/title_activity_edit_project"
android:theme="@style/Theme.AppCompat"
android:parentActivityName="myproject.CountingActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="CountingActivity" />
</activity>
When a user has finished editing they could do one of three things:
- Press a 'save' button. The data are saved, finish() is called and the CountingActivity returns.
- Press the Android back button. The EditProjectActivity is popped off the stack without saving and the Counting Activity returns.
- Press the application icon in the top left. Somehow, the CountingActivity is started without the project_id intent; this value ends up being set to 0 and nothing can be found in the database, with undesirable results.
Somehow, I need to make sure that the project_id is passed as an intent when navigating back to the parent activity. I tried this without luck:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.home) // I also tried R.id.homeAsUp
{
Intent intent = new Intent(EditProjectActivity.this, CountingActivity.class);
intent.putExtra("project_id",project_id);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
But, there's still no project_id and so a database query can't be made. So, if anyone could point me in the right direction I'd appreciate it.
Solution
When you use android.support.PARENT_ACTIVITY
, the parent activity must be set as singleTop
or FLAG_ACTIVITY_CLEAR_TOP
. Otherwise a new instance will be created. See for example Android: Activities destroyed unexpectedly, null savedInstanceState
However, depending on the use case, a simpler alternative may be available. If EditProjectActivity
is always called from CountingActivity
(and never by itself) and you always want to return there, the simplest solution is to just use:
if (id == R.id.home)
{
setResult(...); // optional, whether you want to treat this as save/cancel.
finish();
}
Answered By - matiash
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.