I just want to start a activity on the first run. So after I run it once it should never open again.This Activity is added with
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
so this Activity starts first.
I have a variable which helps me to decide if this Activity started for the first time or not (Im saving it with SharedPreferences which is called sem_first_time).When it is 0 then its the first time if not then this Activity have to finish and start another one.
Here's my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences data = getSharedPreferences("datas",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
first_start = data.getInt("fstart", 0);
if (first_start == 1)
{
finish();
Intent start = new Intent(this, Main.class);
startActivity(start);
}
setContentView(R.layout.first_start);
I got a Button which sets first_start to 1
public void create (View view)
{
SharedPreferences data = getSharedPreferences("datas",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
first_start = 1;
editor.putInt("fstart", first_start);
...
}
But when I start this App once It is showing this Activity again ... What is wrong ?
It is happening because this is the Launcher activity and you are finishing the activity before launching the other activity . It should be like
if (first_start == 1)
{
Intent start = new Intent(this, Main.class);
startActivity(start);
finish();
}
Related
I'm trying to solve an issue passing data between different apps using Intent.
The scenario is like this:
Main (App 1): User clicks Register
Main App launches Register activity (form) in Register (App 2)
User enters first name, last name etc, clicks Send Back
Register app returning values to Main app
Main app displays user's data
Note that Register activity is not the main activity in Register activity.
I would like to solve this without an additional class and without Broadcasting.
My code for Main App, user clicks Register method:
/* User clicks Register */
public void clickRegister(View view) {
Intent intent = new Intent(Intent.ACTION_SEND);
// Verify it resolves
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
boolean isIntentSafe = activities.size() > 0;
// Start an activity if it's safe
if (isIntentSafe) {
startActivity(intent);
}
}
Manifest file for Register activity in Register App:
<activity android:name="com.example.register.Register">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
Now, this is the code in Register activity, of click Send Back method:
/* User clicks Send Back in register activity */
public void clickSendBack(View view) {
// Create an Intent for Register class
// Intent myIntent = new Intent(this, MainActivity.class);
Intent myIntent = new Intent(Intent.ACTION_SEND);
final EditText firstNameInput = (EditText) findViewById(R.id.firstNameEditText);
final EditText secondNameInput = (EditText) findViewById(R.id.secondNameEditText);
String firstName = firstNameInput.getText().toString();
String secondName = secondNameInput.getText().toString();
myIntent.setAction(Intent.ACTION_SEND);
myIntent.putExtra("firstName",firstName);
myIntent.putExtra("secondName",secondName);
myIntent.setType("text/plain");
// Starts activity
startActivity(myIntent);
finish();
}
And here I'm stuck.
Would love to hear any clarification for this topic, and a example for a solution would also be great.
Thanks!
In the first app, add an intent-filter to receive data back from the second app, which is your Register application.
Now, do the same with your Register application, we need to do this so that we can invoke it from our first app.
The intent-filter is there to make sure that we can send data back. According to https://developer.android.com/guide/components/intents-filters:
To advertise which implicit intents your app can receive, declare one or more intent filters for each of your app components with an element in your manifest file.
From the first app, create an Intent that will bring you to the second app. If you don't want to open up the Android share sheet then I suggest you use a PackageManager that gets all the activities that can receive your data and then find in the list your second app and open it with setComponent() with your intent. (Check my code below)
On to our second app, do the same as you did in the first app but now you can add your extras or data like first name and second name.
Back to our first app, write code that will receive the incoming intent from our second app and there, done!
Refer to:
https://developer.android.com/training/sharing
for more information about sending/receiving data with intents.
Here's a sample code:
First Application's Main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Receive your data here from your Register app
Intent receivedIntent = getIntent();
String action = receivedIntent.getAction();
String type = receivedIntent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleReceivedData(receivedIntent);
}
}
}
private void handleReceivedData(Intent intent) {
String firstName = intent.getStringExtra("first_name");
String secondName = intent.getStringExtra("second_name");
if (firstName == null || secondName == null) {
Toast.makeText(this, "Cannot received data!", Toast.LENGTH_SHORT).show();
return;
}
// Do here what you want with firstName and secondName
// ...
Toast.makeText(this, "First name: " + firstName +
" Second name: " + secondName, Toast.LENGTH_SHORT).show();
}
public void open(View view) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,
"Here you can put a message for your 'register' application");
sendIntent.setType("text/plain");
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(sendIntent,
PackageManager.MATCH_DEFAULT_ONLY);
////////////////// Get the other application package name //////////////////
// This is so the user cannot choose other apps to send your data
// In order words, this will send the data back to the other
// application without opening the Android Share sheet
ActivityInfo activityInfo = null;
for (ResolveInfo activity: activities) {
// Specify here the package name of your register application
if (activity.activityInfo.packageName.equals("com.example.registerapp")) {
activityInfo = activity.activityInfo;
break;
}
}
// If the other application is not found then activityInfo will be null
// So make sure you add the correct intent-filter there!
if (activityInfo != null) {
// This will open up your register application
ComponentName name = new ComponentName(activityInfo.applicationInfo.packageName,
activityInfo.name);
sendIntent.setComponent(name);
startActivity(sendIntent);
}
else {
Toast.makeText(this,
"Receiver app doesn't exist or not installed on this device!",
Toast.LENGTH_SHORT).show();
}
}
First Application's Manifest
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
Second Application's Receiver Activity (In this case, your Register app)
Note: as you want, this is NOT the main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receiver);
// This is NOT the main activity!
}
public void send(View view) {
// I just want to note that I am calling the receiving application: "other application"
EditText firstNameEditText = findViewById(R.id.firstNameEditText);
EditText secondNameEditText = findViewById(R.id.secondNameEditText);
String firstName = firstNameEditText.getText().toString().trim();
String secondName = secondNameEditText.getText().toString().trim();
// Check if any of the inputs are empty
if (firstName.isEmpty() || secondName.isEmpty()) {
Toast.makeText(this, "Text boxes cannot be empty!", Toast.LENGTH_SHORT).show();
return;
}
// Send data back to the other application
Intent sendBackIntent = new Intent();
sendBackIntent.setAction(Intent.ACTION_SEND);
sendBackIntent.putExtra("first_name", firstName);
sendBackIntent.putExtra("second_name", secondName);
sendBackIntent.setType("text/plain");
// Get all the available applications that can receive your data
// (in this case, first name and second name)
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(sendBackIntent,
PackageManager.MATCH_DEFAULT_ONLY);
////////////////// Get the other application package name //////////////////
ActivityInfo activityInfo = null;
for (ResolveInfo activity: activities) {
// Specify here the package name of the other application
if (activity.activityInfo.packageName.equals("com.example.mainapp")) {
activityInfo = activity.activityInfo;
break;
}
}
if (activityInfo != null) {
// Same as before, this will open up the other application
ComponentName name = new ComponentName(activityInfo.applicationInfo.packageName,
activityInfo.name);
sendBackIntent.setComponent(name);
startActivity(sendBackIntent);
}
else {
Toast.makeText(this,
"Receiver app doesn't exist or not installed on this device!",
Toast.LENGTH_SHORT).show();
}
}
Second Application's Manifest
<activity android:name=".ReceiverActivity">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
Happy coding!
Edit: I added explanation to my answer.
Your RegisterActivity should look like so
RegisterActivity is parsing the user data to the MainActivity
/* User clicks Send Back in register activity */
public void clickSendBack(View view) {
// Create an Intent for Register class
final EditText firstNameInput =
findViewById(R.id.firstNameEditText);
final EditText secondNameInput =
findViewById(R.id.secondNameEditText);
String firstName = firstNameInput.getText().toString();
String secondName = secondNameInput.getText().toString();
Intent i = new Intent(RegisterActiivty.this, MainActivity.class);
i.putExtra("firstName", firstName);
i.putExtra("secondName", secondName);
startActivity(i);
}
#################################################################
Your MainActivity should look like so.
The MainActivity is responsible for receiving the data
This line of codes should be called in your onCreate method of MainActivity
String firstName = getIntent().getStringExtra("firstName");
String secondName = getIntent().getStringExtra("firstName")
// if you have a TextView on MainActivity you could display the data you have
//gotten from the RegisterActivity like so
Textview firstName = findViewById(R.id.firstName);
firstName.setText(firstName);
Textview secondName = findViewById(R.id.secondName);
secondName.setText(secondName);
/* User clicks Register */
public void clickRegister(View view) {
startActivity(Intent(this, RegisterActivity.class))
}
##########################################################
Your manifest should look like this
<activity android:name="com.example.register.Register"/>
I am trying to wrap my head around what you meant by Main App and Register.
It sound as though they are two different apps or probably two different
project modules. But if what you are trying to say is MainActivity and
RegisterActivity then the above solution should be able to fix your problem.
What you did wrong:
That intent you were trying to parse in the manifest was not needed. If I understood properly what you are trying to achieve. The same goes for the MainActivity and RegisterActivity. You were using Implicit Intent instead of explicit Intent. And when calling findViewById this extra (EditText) was not needed because it is redundant. For more on the intent you can check this
However, this guide should be useful to anyone seeking to parse data from one activity to another.
This question already has answers here:
How to use NFC ACTIONS
(5 answers)
Closed 3 years ago.
I made app that detects nfc tag. All work fine, when my app is closed and i scan the nfc tag with my phone it shows me an activity have onCreate() method , when i scan again for the 2nd time it works , i dont know if im wrong in the lifecycle of the app or that i missed something in my code?
when i open app , scanning is working : 1st photo
when app is closed 2nd photo : from 2nd photo but in the 2nd scan it works
this is my code
public class NfcActivity extends AppCompatActivity {
private static final String TAG = "NfcActivity";
private NfcAdapter mNfcAdapter;
private TextView mTextView;
PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nfc);
mTextView = findViewById(R.id.tv_nfc_detail);
mNfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
if (mNfcAdapter == null) {
Toast.makeText(this, "Cet appareil ne supporte pas nfc", Toast.LENGTH_SHORT).show();
finish();
return;
}
if (!mNfcAdapter.isEnabled()) {
startActivity(new Intent("android.settings.NFC_SETTINGS"));
Toast.makeText(this, "Activer nfc", Toast.LENGTH_SHORT).show();
}
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
#Override
protected void onPause() {
super.onPause();
mNfcAdapter.disableForegroundDispatch(this);
}
#Override
protected void onResume() {
super.onResume();
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter[] intentFilters = new IntentFilter[]{};
mNfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, null);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
Tag iTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
mTextView.setText(TagReader.readTag(iTag, intent));
}
// }
}
}
<activity android:name=".Activities.NfcActivity" android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>
</activity>
Edit: see full solution in related:
How to use NFC ACTIONS
You are only processing the intent the 2nd time round.
Add a new method based on your current onNewIntent() method like this:
private void onNewNfcTag(Intent intent) {
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())
|| NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
Tag iTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
mTextView.setText(TagReader.readTag(iTag, intent));
}
}
Change your onNewIntent() to call this new method:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
onNewNfcTag(intent);
}
Call this same method from onCreate() with the intent from getIntent():
#Override
protected void onCreate(Bundle savedInstanceState) {
// .... your code already here
onNewNfcTag(getIntent());
}
I am working on notification and I have a problem. I have an activity already open when I click on notification I don't want to open it again just update the current activity.
if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
Intent pushNotification = null;
if (NotificationType != 0 && NotificationType != 2 && NotificationType != 5 && NotificationType != 26) {
pushNotification = new Intent(getApplication(), SplashScreen.class);
pushNotification.putExtra("NotificationType", NotificationType);
pushNotification.putExtra("ReferenceID", ReferenceID);
pushNotification.putExtra("NotificationID", ReferenceID);
pushNotification.putExtra("isread", ReferenceID);
showNotificationMessage(getApplicationContext(), title, message, time, pushNotification);
} else if (NotificationType == 0 || NotificationType == 2 || NotificationType == 5 || NotificationType == 26) {
showNotificationMessageWithNoAction(getApplicationContext(), title, message, title, null);
}
}
can Anyone tell me how I update the activity when I click on notification?
You just need to declare the launchMode to the singleTask to make ensure that multiple same screens not will open.
There are four launch modes for activity. They are:
1. Standard
2. SingleTop
3. SingleTask
4. SingleInstance
Please refer this link Click here
<activity android:name="YOUR_SPLASH_ACTIVITY"
android:launchMode="singleTask"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
And in the Java code , you just override the onNewIntent method , to refresh activity,
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
/**
* HERE YOU JUST REFRESH , YOUR ACTIVITY
*/
}
I don't know if this is what you need but you can do this
finish();
startActivity(getIntent());
Let me know what you really need.
EDIT:
If you need to keep your activity state intact, you can do this
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("MyString", "Welcome back to Android");
}
This will save your activity state
And then you retrieve UI state like this
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
String myString = savedInstanceState.getString("MyString");
}
Best way is to make use of the onNewIntent(Intent) method of your Activity.
You can use the Intent parameter of this method to get your Intent Extras, because getIntent() will give the Intent that started the Activity in the first place.
public class MainActivity extends Activity {
public void onCreate(Bundle SavedInstanceState) {
//Initial loading
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if(intent.getStringExtra("methodName").equals("myMethod")) {
//Update the existing screen
}
}
}
I am trying to get NFC foreground dispatch to work in my app using the tutorials
here and here. From what I can deduce all other functions seem to be working a it is just the NFC forground dispatch system that isn't working.
In my onCreate, I check NFC exists and initialise pending Intents and filters and get the NFC adapter:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set some stuff
mTV = (TextView) findViewById(R.id.textView);
mButt = (Button) findViewById(R.id.button);
//mNfcAd = NfcAdapter.getDefaultAdapter(this);
//Init elsewhere
getAdapter();
//Hide button until its needed
mButt.setVisibility(View.INVISIBLE);
//Make sure NFC actually exists.....
if (mNfcAd == null) {
//Not going to work without NFC
Toast.makeText(this, "This device does not support NFC\nGet used to the pen and paper for now :/", Toast.LENGTH_LONG).show();
finish();
return;
}
Intent nfcIntent = new Intent(this, getClass());
nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
nfcPendingIntent =
PendingIntent.getActivity(this, 0, nfcIntent, 0);
IntentFilter tagIntentFilter =
new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
tagIntentFilter.addDataType("text/plain");
intentFiltersArray = new IntentFilter[]{tagIntentFilter};
}
catch (Throwable t) {
t.printStackTrace();
}
//Init the prefs
initPrefs();
}
public void initPrefs() {
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
}
private NfcAdapter getAdapter(){
if(mNfcAd ==null){
NfcManager manager = (NfcManager) getSystemService(NFC_SERVICE);
mNfcAd = manager.getDefaultAdapter();
}
return mNfcAd;
}
I then go on to check NFC is enabled (if not display a button that shows NFC settings) as well as checking if the app is in its first run. At the end of onResume(), I (attempt to) enable Foreground Dispatch for the adapter.
protected void onResume() {
super.onResume();
//Define the mButt action
mButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent dialogIntent = new Intent(Settings.ACTION_NFC_SETTINGS);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
}
});
//If NFC exists, check if its turned on
if (!mNfcAd.isEnabled()) {
Toast.makeText(this, "You have NFC, but you haven't enabled it...", Toast.LENGTH_LONG).show();
mTV.setText("NFC not enabled");
mButt.setVisibility(View.VISIBLE);
}
//Check if first run
if (prefs.getInt("firstTime", 1) == 1 ||
prefs.getString("fullName", null) == null ||
prefs.getString("house", null) == null) {
Intent intent = new Intent(this, First_Run.class);
startActivity(intent);
prefs.edit().putInt("firstTime", 0);
prefs.edit().putString("fullName", getIntent().getExtras().getString("fullName"));
prefs.edit().putString("house", getIntent().getExtras().getString("house"));
prefs.edit().apply();
}
getAdapter().enableForegroundDispatch(this, nfcPendingIntent, intentFiltersArray, null);
handleIntent(getIntent());
}
The error is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.nfc.NfcAdapter.enableForegroundDispatch(android.app.Activity, android.app.PendingIntent, android.content.IntentFilter[], java.lang.String[][])' on a null object reference
However, all the arguments seem to be initialised;
It is being called in onResume, so the activity context is created;
nfcPendingIntent and intentFiltersArray are initialised in onCreate;
I do not have a techlist so I use null as the final argument;
The adapter itself is initialised in getAdapter.
I am currently combing through other tutorials to see the different methods that can be used, however I would really like to get this fixed.
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-feature
android:name="android.hardware.nfc"
android:required="true" />
<uses-permission android:name="android.permission.NFC" />
<application
android:fullBackupContent="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
<activity
android:name=".First_Run"
android:label="#string/title_activity_first__run">
</activity>
</application>
Try creating your NfcAdapter object like below.
NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
In my app, I model Lists of items. In MainActivity, I see ListView containing Lists. I can click on each list to see its items (DisplayListActivity). On DisplayListActivity, I have button in the ActionBar to display the list properties. This launches the third activity (EditListPropertiesActivity).
Main
| ^
V |
DisplayListActivity (listId is passed with Intent, default=1)
| ^
V |
EditListPropertiesActivity (listId is passed with Intent, default=1)
The problem appears, when I select List id=2 on the MainActivity, and then I select the properties button on the DisplayListActivity. Once I am done with the EditListPropertiesActivity, i click '<' (back) on the ActionBar: .
I return to the DisplayListActivity, but instead of going back to the list id=2, I see the list with id=1 (which is default).
How to pass the ListId back form EditListPropertiesActivity to the DisplayListActivity?
startActivityForResult and return the id - would work, but I see it ugly
use the SharedPreferences and store sth like lastVisitedList - ugly
store the lastVisitedList information in the db - even uglier
What is the usual solution for that problem?
Code snippets below.
MainActivity
public class MainActivity extends Activity {
...
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
MetaList mlist = (MetaList) listView.getItemAtPosition(i);
final Intent intent;
intent = new Intent(getApplicationContext(), DisplayListActivity.class);
intent.putExtra(META_LIST_SELECTED, mlist.getId());
startActivity(intent);
}
}
);
...
DisplayListActivity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list);
intent = getIntent();
metaListId = intent.getLongExtra(MainActivity.META_LIST_SELECTED, 1); //read the data or take 1 as default
...
//start the third activity
final Intent intent;
intent = new Intent(getApplicationContext(), EditListPropertiesActivity.class);
intent.putExtra(META_LIST_SELECTED, metaListId);
startActivity(intent);
....
EditListPropertiesActivity
public class EditListPropertiesActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_list_parameters);
getActionBar().setDisplayHomeAsUpEnabled(true); //this enables the '<' (back) button
intent = getIntent();
metaListId = intent.getLongExtra(DisplayMetaListActivity.META_LIST_SELECTED, 1);
...
Manifest
<application>
<activity
android:name=".MainActivity">
</activity>
<activity
android:name="com.example.tutorial1.DisplayListActivity"
android:parentActivityName="com.example.tutorial1.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.tutorial1.MainActivity" />
</activity>
<activity
android:name="com.example.tutorial1.EditListPropertiesActivity"
android:parentActivityName="com.example.tutorial1.DisplayListActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.tutorial1.DisplayListActivity" />
</activity>
</application>
try this to finish an activity
Intent intent = new Intent();
intent.putExtra(EXTRA, value);
setResult(RESULT_OK, output);
finish();
and this for getting the result in the previous activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data.getExtras().containsKey(EXTRA)){
// do stuff with data from finished activity
String bla = data.getStringExtra(EXTRA)
}
}
EDIT: read comments! need to use startActivityForResult
try to call finish(); that you should call on destroy of the current activity and display the previous activity.
I have found the solution that works. I post it here, because it is cleaner (in my opinion) and different than the other proposed. I set the launch mode of the second activity to singleTask in the manifest file: android:launchMode="singleTask"
...
<activity
android:name="com.example.tutorial1.DisplayListActivity"
android:label="Meta List"
android:parentActivityName="com.example.tutorial1.MainActivity"
android:launchMode="singleTask">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.tutorial1.MainActivity" />
</activity>
...
If there is a better solution for the stated problem, I am open for discussion :)