Same activity getting stacked - java

I have an activity that is suppose to finish itself and close the application. Now, in certain cases, which are varying on how the user is navigating to the activity, the activity is getting stacked. When the activity is stacking up, then calling finish() or android.os.Process.killProcess(android.os.Process.myPid()); or both together is only showing up the same activity again.
The Manifest:
<activity
android:name="newActivities.HomeActivity"
android:label="#string/title_activity_home"
android:screenOrientation="portrait">
</activity>
The activity:
public class HomeActivity extends Activity {
private EditText studentNameEdittext;
private Button startYourStoryButton, loginButton, navCollegesButton, settingsButton, search_friends_button, browseStoriesButton;
private TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// if (getFromPreference("loginStatus").equalsIgnoreCase("true")) {
// finish();
// saveInPreference("loginStatus", "");
// }
// Set up the action bar
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#009945")));
bar.setTitle("Study Story");
bar.setIcon(R.drawable.statusbar_icon);
int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTextColor(getResources().getColor(R.color.white_colour));
yourTextView.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// studentNameEdittext = (EditText)
// findViewById(R.id.studentNameEdittext);
startYourStoryButton = (Button) findViewById(R.id.startYourStoryButton);
// loginButton = (Button) findViewById(R.id.loginButton);
navCollegesButton = (Button) findViewById(R.id.navCollegesButton);
// settingsButton = (Button) findViewById(R.id.settingsButton);
// search_friends_button = (Button)
// findViewById(R.id.search_friends_button);
browseStoriesButton = (Button) findViewById(R.id.browseStoriesButton);
// textView1 = (TextView) findViewById(R.id.textView1);
// Set up font type
// studentNameEdittext.setTypeface(TypeFaceController.generalTextFace(HomeActivity.this));
startYourStoryButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// loginButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
navCollegesButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// settingsButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// search_friends_button.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
browseStoriesButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// textView1.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
startYourStoryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
Intent i = new Intent(HomeActivity.this, SignUp.class);
i.putExtra("signUpCaller", "Home");
startActivity(i);
}
});
// loginButton.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View arg0){
// Intent i = new Intent(HomeActivity.this, Login.class);
// startActivity(i);
// }
// });
// search_friends_button.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v){
// Intent i = new Intent(HomeActivity.this,
// FindStudentBrowseStoryActivity.class);
// i.putExtra("Button", "search_friends_button");
// i.putExtra("searchString", studentNameEdittext.getText().toString());
// startActivity(i);
//
// }
// });
browseStoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent i = new Intent(HomeActivity.this, FindStudentBrowseStoryActivity.class);
i.putExtra("Button", "browseStoriesButton");
startActivity(i);
}
});
navCollegesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent i = new Intent(HomeActivity.this, CollegeListActivity.class);
startActivity(i);
}
});
// settingsButton.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v){
// Intent i = new Intent(HomeActivity.this, HomeSettingsActivity.class);
// i.putExtra("FromActivity", "HomeSettingsActivity");
// startActivity(i);
// finish();
//
// }
// });
}
// #Override
// protected void onStart(){
// if (getFromPreference("loginStatus").equalsIgnoreCase("true")) {
// finish();
// }
// super.onStart();
// }
//
// #Override
// protected void onResume(){
// if (getFromPreference("loginStatus").equalsIgnoreCase("true")) {
// finish();
// }
// super.onResume();
// }
// =========Login button action bar
#Override
public boolean onCreateOptionsMenu(Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_menu, menu);
return true;
}
// =========Login button action bar
#Override
public boolean onOptionsItemSelected(MenuItem item){
// handle item selection
switch (item.getItemId()) {
case R.id.home_login_string:
Intent i = new Intent(HomeActivity.this, Login.class);
// finish();
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// logic to fix logout
#Override
public void onBackPressed(){
// Intent startMain = new Intent(Intent.ACTION_MAIN);
// startMain.addCategory(Intent.CATEGORY_HOME);
// startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);;
// startActivity(startMain);
//
// int pid = android.os.Process.myPid(); //
// android.os.Process.killProcess(pid); // return; }
android.os.Process.killProcess(android.os.Process.myPid());
finish();
}
// method to save variable in preference
public void saveInPreference(String name, String content){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(name, content);
editor.commit();
}
// getting content from preferences
public String getFromPreference(String variable_name){
String preference_return;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preference_return = preferences.getString(variable_name, "");
return preference_return;
}
}
Please tell me where am I going wrong? Why is the activity stacking?
P.S: We cannot use single top etc as it causes some transition issues with the existing custom theme!

Take one application class which extends Application and take one arrayList and maintain the references of the activities in the arraylist.
When you click on back button in desired activity then finish the all the activities using arraylist.
Take one base activity. Which is super class of all the activities
public class BaseActviity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
App application = (App) getApplication();
application.addActivity(this);
}
}
Take one application class
public class App extends Application {
public App() {
if (listActivty == null) {
listActivty = new ArrayList<BaseActviity>();
}
}
public ArrayList<BaseActviity> listActivty;
public void addActivity(BaseActviity actviity) {
if (!listActivty.contains(actviity)) {
listActivty.add(actviity);
}
}
}
take 4 samples activity classes like ......
1) public class FirstActivity extends BaseActviity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
}
public void send(View view) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
2) public class SecondActivity extends BaseActviity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
}
public void send(View view) {
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
}
3).........................
4) ............................
in 4 th activity class placed the following code
In desire activity that means final activity,override the onBackPressed
public void onBackPressed() {
super.onBackPressed();
App application = (App) getApplication();
ArrayList<BaseActviity> listActivty = application.listActivty;
for (BaseActviity actviity : listActivty) {
actviity.finish();
}
}

Wherever you are opening the activity which is getting stacked up, use this:
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

Check if the Activity, that would be last activity when user clicks on the back button,is visible or not and if visible use
System.exit(0);

At last, the problem is solved. I has to do a little trick:
ParseUser.getCurrentUser();
ParseUser.logOut();
Intent i = new Intent(getActivity(), NewHomeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
getActivity().startActivity(i);
getActivity().finish();
This did not cause any transition issues as well.

Related

Go To Existing Fragment from Opened Child Activity

I have an app that has two tabs with fragments. One tab is called map and the other restaurantList. When I click on map marker or a card in the list it opens a restaurantDetailsActivity that has info about restaurant - lat, lang, name, rating, etc. There I have a floating action button that the user should click and it should close the current activity and go to maps tab fragment, to the location that I passed from the activity. I have tried a lot of stuff without any success: 1 2 3 4 5 6 7 8 9 ...
This is what I would want - when the user clicks the FAB, it should pass lat and lon from the restaurantDetailsActivity, to my map fragment and zoom in into that location (based on the lat and lon), regardless whether it was opened from the list fragment or the map fragment.
My restaurantDetailsActivity:
final String lat = restaurant.getLat();
final String lon = restaurant.getLon();
FloatingActionButton fabGoToMap = findViewById(R.id.fabGoToMap);
fabGoToMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// MapsFragment fragment = new MapsFragment();
// Bundle bundle = new Bundle();
// bundle.putString("lat", lat);
// bundle.putString("lon", lon);
// MapsFragment mapsFragment = new MapsFragment();
// mapsFragment.setArguments(bundle);
// Intent restaurantDescriptionIntent = new Intent(this, MapsFragment.class);
Bundle bundle = new Bundle();
bundle.putString("lat", lat);
bundle.putString("lon", lon);
MapsFragment fragInfo = new MapsFragment();
fragInfo.setArguments(bundle);
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// transaction.add(R.id.map, mapsFragment, "tag").commit();
finish();
}
});
UPDATED CODE:
Calling the activity from list fragment:
public void fetchRestaurant(String restaurantId) {
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<RestaurantResponse> call = apiService.getRestaurantById(restaurantId);
call.enqueue(new Callback<RestaurantResponse>() {
#Override
public void onResponse(Call<RestaurantResponse> call, retrofit2.Response<RestaurantResponse> response) {
final Restaurant restaurant= response.body().getResults();
Intent intent = new Intent(getActivity().getApplicationContext(), AvailableRestaurantActivity.class);
intent.putExtra("estaurant", estaurant);
startActivity(intent);
}
#Override
public void onFailure(Call<RestaurantResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
Toast.makeText(getActivity().getApplicationContext(), R.string.failed_connectivity, Toast.LENGTH_LONG).show();
}
});
}
My main activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tutorialUsed = false;
tutorialPage = 1;
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
} else {
List<restaurant> restaurants = new ArrayList<>();
TabLayout tabLayout = findViewById(R.id.sliding_tabs);
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_one)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_two)));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
final ViewPager viewPager = findViewById(R.id.viewpager);
PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setOffscreenPageLimit(3);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
});
....
myUserName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent accountIntent = new Intent(MainActivity.this, MyProfileActivity.class);
startActivity(accountIntent);
}
});
}
}
Start restaurantDetailactivity from your MainActivity using startActivityForResult like this
startActivityForResult(intent, SHOW_DETAILS_REQUEST);
Click on FAB should be like this
final String lat = restaurant.getLat();
final String lon = restaurant.getLon();
FloatingActionButton fabGoToMap = findViewById(R.id.fabGoToMap);
fabGoToMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("lat", lat);
bundle.putString("lon", lon);
intent.putExtras(bundle);
setResult(Activity.RESULT_OK,intent);
}
});
in your MainActivity handle activity result like below
#Override
protected void onActivityResult(final int requestCode,
final int resultCode,
final Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case SHOW_DETAILS_REQUEST: {
//select mapfragment as current, assuming it is at index 0
viewpager.setCurrentItem(0);
//add your zoom logic here in zoomToCenter method
mapfragment.zoomToCenter(data.getStringExtra("lat"),data.getStringExtra("lon"));
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Kemo, You have an event that takes place in a fragment and as a result of the event you want the activity to swap one fragment for a second fragment. So your problem is how to communicate from fragment to activity. The fragment's on attach will give you the context for the activity. The activity should have a method to swap fragments in and out and using the context you got in the on attach you can use in the fragments oncreateview and run the activity's method.here Good luck professor

Get certain intents

So lets say i have 4 buttons , and each button contains an intent which navigates to an activity.They all navigate to a single same activity . When i click the first button i want that new activity to show "Hi" , When i click the second button i want it to show "Bye" and so on . How do i do that ?
Here is a simple code to start with
public class Intentt extends Activity {
Button b1,b2,b3,b4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intentt);
b1 = (Button)findViewById(R.id.button2);
b2 = (Button)findViewById(R.id.button3);
b3 = (Button)findViewById(R.id.button4);
b4 = (Button)findViewById(R.id.button5);
b1.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
startActivity(i);
}
});
b2.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
startActivity(i);
}
});
b3.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
startActivity(i);
}
});
b4.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
startActivity(i);
}
});
}
Just pass some data through intent extras, or intent extra Bundle:
Intent i=new Intent(context,MainActivity.class);
i.putExtra(id, 453);
context.startActivity(i);
Example:
Button b1, b2, b3, b4;
Context context = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intentt);
b1 = (Button) findViewById(R.id.button2);
b2 = (Button) findViewById(R.id.button3);
b3 = (Button) findViewById(R.id.button4);
b4 = (Button) findViewById(R.id.button5);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, MainActivity.class);
i.putExtra(MainActivity.ID_ACTION, MainActivity.ACTION_1);
startActivity(i);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, MainActivity.class);
i.putExtra(MainActivity.ID_ACTION, MainActivity.ACTION_2);
startActivity(i);
}
});
}
And then in that activity you can switch on that values getting them like that:
String id = intent.getStringExtra("id");
int id = intent.getIntExtra("id",-1);
and then use the if-elseif-else or switch statement(s) to change the actions based on the passed action, so you can display your messages
To properly recieve them you need to set activity's launchMode to "standard" because of this bug in AndroidManifest.xml and create
public static final int ACTION_1 = 1;
public static final int ACTION_2 = 2;
public static final int ACTION_NULL = -1;
public static final String ID_ACTION = "action_id";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int id = getIntent().getIntExtra(ID_ACTION, -1);
if (id == ACTION_NULL) {
Log.d("TAG", "id is null");
Toast.makeText(MainActivity.this, "id is null!", Toast.LENGTH_SHORT).show();
} else if (id == ACTION_1) {
Log.i("TAG", "ALLOHA! from button 1");
Toast.makeText(MainActivity.this, "Aloha from button 1!", Toast.LENGTH_LONG).show();
} else if (id == ACTION_2) {
Log.i("TAG", "Hello from button 2");
Toast.makeText(MainActivity.thi,"Hello from button 2!", Toast.LENGTH_LONG).show();
}
}
In each intent you could pass parameterts
Intent i=new Intent(context,SendMessage.class);
i.putExtra("KEY_MESSAGE", "Hola amigo");
In the other activity
Intent i = getIntent();
String message = i.getStringExtra("KEY_MESSAGE")
Toast.make(this,message,Toast.LENGTH_SHORT).show()
Re write the button click listener as follows :
b1.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra("Data","Hi");
startActivity(i);
}
});
b2.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra("Data","Hello");
startActivity(i);
}
});
b3.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra("Data","Bye");
startActivity(i);
}
});
b4.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra("Data","See you");
startActivity(i);
}
});
In your MainActivity class onCreate Method, you can access the passed data by :
String passedData = getIntent().getStringExtra("Data");
you can use this passedData to display on screen.
Do it like this:
public class Intentt extends Activity implements View.OnClickListener {
Button b1,b2,b3,b4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intentt);
b1 = (Button)findViewById(R.id.button2);
b2 = (Button)findViewById(R.id.button3);
b3 = (Button)findViewById(R.id.button4);
b4 = (Button)findViewById(R.id.button5);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button2:
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra('"STRING_I_NEED"', "Hi");
startActivity(i)
break;
case R.id.button3:
Intent i = new Intent(Intentt.this,MainActivity.class);
i.putExtra('"STRING_I_NEED"', "Bye");
startActivity(i)
break;
case R.id.button4:
break;
.
.
.
}
}
}
After that in your mainActivity retrieve string that you sent with:
Bundle extras = getIntent().getExtras();
String s = extras.getString("STRING_I_NEED");

Pass a XML resource from one activity to another activity using java code in Android Studio?

I want to pass an XML resource from one activity to another activity using Java Code? I don't want to create separate different activities for different buttons.
ImageButton imageBttn = (ImageButton)findViewById(R.id.imageButton1);
imageBttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, info.class));
}
});
Pseudocode to explain what I'm trying to do:
If BUTTON_1 is clicked
-Pass swirl.png to info.class
If BUTTON_2 is clicked
-Pass golden.png to info.class
If BUTTON_3 is clicked
-Pass arcade.png
imageBttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, info.class)
intent.putExtra("image",R.drawable.ic_search_grey);
startActivity(intent);
}
});
On Mainactvitiy get the int drawable
int res = getIntent().getIntExtra("image", -1);
if(res > -1) {
Drawable drawable = getResources().getDrawable(res, null);
imgBtn.setImageDrawable(drawable);
}
InfoActivity.java
public class InfoActivity extends Activity {
private static final String EXTRA_IMAGE = "image";
public static void launch(Activity activity, #DrawableRes int imageResId) {
Intent intent = new Intent(activity, InfoActivity.class);
intent.putExtra(EXTRA_IMAGE, imageResId);
activity.startActivity(intent);
}
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
int imageResId = getIntent().getIntExtra(EXTRA_IMAGE, -1);
if (imageResId == -1) {
throw new IllegalArgumentException(EXTRA_IMAGE);
// or set error/default image resource id
}
// ... something to do with imageResId
}
}
MainActivity.java
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InfoActivity.launch(MainActivity.this, R.drawable.swirl);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InfoActivity.launch(MainActivity.this, R.drawable.golden);
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InfoActivity.launch(MainActivity.this, R.drawable.arcade);
}
});
}

Remove activities manually from Android app stack

I been working on Android Native App , What i was trying to do is :
Activities - A -> B -> C Then A-> B -> C -> C .
From C Activity if it again point to C then i want to remove C , B from stack manually .
On my back it should move only to A .
I tried finish() but problem is :
Activities - A -> B -> C Then A-> B -> C -> C on finish A -> B -> C required state A-> C .
Is anyone know how to catch all activities in stack and remove specific activities from stack ??
In Activity C, override onBackPressed and add in something like:
#Override
public void onBackPressed() {
if (shouldGoBackToA) { // There are various ways this could be set
Intent intent = new Intent(this, AActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
finish();
}
}
FLAG_ACTIVITY_CLEAR_TOP will cause it to go down the stack to the existing copy of A Activity instead of starting a new one. From the docs:
public static final int FLAG_ACTIVITY_CLEAR_TOP
If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
While calling intent pass a flag called actvity clear top like this:
Intent newIntent=new Intent(this,MainActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(newIntent);
You can use this :
In A activity while passing to B activity, the intent should be added with a flag FLAG_ACTIVITY_NO_HISTORY like this,
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent newIntent=new Intent(AActivity.this,Bactivty.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(newIntent);
}
});
While moving to CActivity:
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent newIntent = new Intent(Bactivty.this, CActivity.class);
startActivity(newIntent);
}
});
On backpress will take you to AActivity now.
Step 1: Start activty for result A -> B -> C1 -> C2..
Call your Activity with startActivityForResult
Intent intent = new Intent(yourActivity.this, nextActivity.class);
startActivityForResult(intent, 1);
Step 2: In C2 specify that you want to go back to A..
Whenever you are done with your activity write the below code
Intent i = getIntent();
i.putString("Result","GottoA");
setResult(Activity.RESULT_OK, i);
finish();
Step 3: Whenever C2 finishes , previsus stack activit's onActivityResult is called.. so u can check in C1 and B onActivityResult whether you have set any result bck.. and finish accordingly
and impliment the following code in Activity B and c
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Intent i = getIntent();
if (resultCode == RESULT_OK && i.getString("Result","null").equals"GottoA") {
i.putString("Result","GottoA");
setResult(RESULT_OK, i);
finish();
}
}
In Activity C, when back button is pushed start activity A like this:
#Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), A.class);
intent.putExtra("EXIT", true);
startActivity(intent);
}
Then in Activity A's onCreate() do this
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
this complete example may help you...
public class ActivityA extends Activity {
public static final int ID_TEXTVIEW = 0xDEAF1;
public static final int ID_BUTTON = 0xDEAF2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = getContentView(this);
TextView textView = (TextView) contentView.findViewById(ID_TEXTVIEW);
textView.setText("ActivityA");
setContentView(contentView);
final Button button = (Button) contentView.findViewById(ID_BUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivity(intent);
}
});
}
public static View getContentView(Context context) {
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
TextView textView = new TextView(context);
textView.setLayoutParams(layoutParams);
textView.setId(ID_TEXTVIEW);
layout.addView(textView);
Button button = new Button(context);
button.setText("Next");
button.setLayoutParams(layoutParams);
button.setId(ID_BUTTON);
layout.addView(button);
return layout;
}
}
public class ActivityB extends Activity {
public static final String ACTION_FINISH = "com.myapp.test2.ACTION_FINISH";
public ActivityB() {
}
private FinishReceiver finishReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = ActivityA.getContentView(this);
final TextView textView = (TextView) contentView
.findViewById(ActivityA.ID_TEXTVIEW);
textView.setText("ActivityB");
setContentView(contentView);
final Button button = (Button) contentView
.findViewById(ActivityA.ID_BUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActivityB.this, ActivityC.class);
startActivity(intent);
}
});
finishReceiver = new FinishReceiver();
IntentFilter filter = new IntentFilter(ACTION_FINISH);
registerReceiver(finishReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(finishReceiver);
}
private class FinishReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_FINISH)) {
finish();
}
}
}
}
public class ActivityC extends Activity {
public ActivityC() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = ActivityA.getContentView(this);
final TextView textView = (TextView) contentView
.findViewById(ActivityA.ID_TEXTVIEW);
textView.setText("ActivityC");
setContentView(contentView);
final Button button = (Button) contentView.findViewById(ActivityA.ID_BUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActivityB.ACTION_FINISH);
sendBroadcast(intent);
intent = new Intent(ActivityC.this, ActivityC.class);
startActivity(intent);
finish();
}
});
}
}

button click event doesnt work

I'm trying to switch the views, but when I'm in the second view, the back event click doesnt work.. I don't know what's wrong.
Pls, see my code and help me!
Part1
Part2
public class t extends Activity implements OnClickListener {
Button volta;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.janela2);
volta = (Button) findViewById(R.id.button2);
volta.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == volta) {
startActivity(new Intent(t.this, MainActivity.class));
}
}
}
You have to override onBackPressed. Change your MainActivity as below
public class MainActivity extends Activity {
private boolean goBack = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sobre = (Button) findViewById(R.id.button1);
sobre.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
goBack = true;
setContentView(R.layout.janela2);
}
});
}
#Override
public void onBackPressed() {
//If you have switched to R.layout.janela2 then go back
if (goBack){
setContentView(R.layout.activity_main);
goBack = false;
return;
}
//else do default action
super.onBackPressed();
}
}
Just do the following code, I hope it might help you
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sobre = (Button) findViewById(R.id.button1);
sobre.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, t.class);
startActivity(intent);
}
});
}
}
In t.java
public class t extends Activity{
Button volta;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.janela2);
}
#Override
public void onStop() {
super.onStop();
finish();
}
}
If you want two layouts then use viewflipper. If you want two activities (java classes) AND two layouts separately then use:
Intent i = new Intent (this, myClass.class);
startActivity(i);
To start the Activity and NOT setcontentview
So here:
public void onClick(View v) {
startActivity(new Intent (MainActivity.this, t.class));
OR IN THE CASE OF T.CLASS:
startActivity(new Intent (t.this, MainActivity.class));
}
You have to override onBackPressed() method if you want to back button functionality in your application. i.e.
public void onBackPressed() {
Intent start = new Intent(CurrentClass.this,Next_Activity.class);
startActivity(start);
finishActivity(0);
}

Categories

Resources