I have an activity which starts when my app is first launched(Only once).The activity lets the users select the topics.Then when they press done, I finish() the activity.This leads the user to the MainActivity.But when the user press the back button it goes back to the activity which was first launched(the activity which I closed using finish()).But what i want is that the app should close when the user presses the back button from the MainActivity(always).I overrided onBackPressed in both the classes.
My onBackPressed method in both the classes looks like this:
#Override
public void onBackPressed() {
finish();
}
MainActivity(Relevant part of code):
public class MainActivity extends AppCompatActivity
{
TopicAdapter adapter;
private AdView mAdView ;
//-------GLOBAL VARIABLES-------------------
AdRequest adRequest;
ArrayList<Sections> gameList = new ArrayList<>();
String json;
//-------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences =
getSharedPreferences("ShaPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
boolean firstTime=sharedPreferences.getBoolean("first", true);
//Launch the topics selection activity for the first time
if(firstTime)
{
editor.putBoolean("first",false);
editor.commit();
Intent intent = new Intent(MainActivity.this, channels_activity.class);
intent.putExtra("isFirst",true);
startActivity(intent);
}
}
#Override
public void onBackPressed()
{
finish();
}
}
You just need to call finish()
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
And Set android:noHistory="true" on the activity in your manifest
See here
Related
After pressing the button I would like to go to the second activity, enter the data in the second activity and then return to the main activity, but having data in ListView. This is my code:
MainActivity:
public class MainActivity extends AppCompatActivity {
Button button;
ListView listView;
String name;
private static final int REQUEST_CODE = 1;
ArrayAdapter<String> adapter;
ArrayList<String> nameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button2);
listView = findViewById(R.id.CarList);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(i, REQUEST_CODE);
}
});
nameList = new ArrayList<String>();
nameList.addAll(Arrays.asList(name));
adapter = new ArrayAdapter<String>(this, R.layout.element, nameList);
listView.setAdapter(adapter);
}
protected void onActivityResult(int requestCode, int resultCode, Intent i){
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
name = i.getStringExtra("name");
}
}
}
And this is my SecondActivity:
public class SecondActivity extends AppCompatActivity {
EditText editText;
Button button2;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
editText = findViewById(R.id.editText);
button2 = findViewById(R.id.button);
}
public void finish() {
Intent i = new Intent();
name = editText.getText().toString();
i.putExtra("name", name);
setResult(RESULT_OK, i);
super.finish();
}
}
What could I change to make the application work? Because now I only get the message that: app has stopped, but I don't receive information about any error.
After pressing the button I would like to go to the second activity, enter the data in the second activity and then return to the main activity, but having data in ListView.
What could I change to make the application work? Because now I only get the message that: app has stopped, but I don't receive information about any error.
This is simply because you've incorrectly thinking that Activity.finish() is always called whenever you close the activity. But it never be called by the Android. Take a look for this Lifecyle picture from Activity-lifecycle concepts:
you can see that only onStop() then onDestroy() is called when activity is closed.
You need to call the finish() method manually to send your intent. Or, the better way, create a method that only build and set the intent for the result. Something like this:
private void prepareResult(String name) {
Intent i = new Intent();
i.putExtra("name", name);
setResult(RESULT_OK, i);
}
then call it whenever you want to close your activity:
String name = editText.getText().toString();
prepareResult(name);
finish();
Or you can override the onBackPressed() to also handing the back pressed, like the following:
#Override
public void onBackPressed() {
Intent i = new Intent();
name = editText.getText().toString();
i.putExtra("name", name);
setResult(RESULT_OK, i);
// The default implementation simply finishes the current activity
// see the documentation.
super.onBackPressed();
}
This question already has answers here:
How to finish Activity when starting other activity in Android?
(7 answers)
Closed 3 years ago.
I have an activities:
Activity1, that should be opened once (first launch)
Activity2, the main screen.
After doing some things in Activity1 on first launch, every next launch Activity2 should be opened.
I kinda figured out how to do this, and it works perfectly, but when I press "back" button on my phone, Activity1 suddenly appears.
So how can I fix it? Should I clear stack or what?
Here's my code:
Activity1:
public class MainActivity extends AppCompatActivity {
Button but1;
EditText input1;
TextView error1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_page);
if(getName("username")!=null){
Intent intent = new Intent(MainActivity.this, WelcomePageLast.class);
startActivity(intent);
}
ListenerOnButton();
}
public void ListenerOnButton(){
but1 = (Button)findViewById(R.id.welcome_page_button);
input1 = (EditText)findViewById(R.id.username_input);
error1 = (TextView)findViewById(R.id.name_error);
but1.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view){
if (input1.getText().toString().length() < 2){
error1.setText("Слишком короткое имя!");
}else {
error1.setText("");
Intent intent = new Intent(MainActivity.this, WelcomePageLast.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP);
setName("username", input1.getText().toString());
startActivity(intent);
}
}
}
);
}
public void setName(String key, String value){
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply();
}
public String getName(String key){
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
return preferences.getString(key, null);
}
}
Activity2:
public class WelcomePageLast extends AppCompatActivity {
TextView greetings;
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences prefs = getSharedPreferences("preferences", MODE_PRIVATE);
String greeting_message = getString(R.string.greetings_message) + prefs.getString("username", "") + "!";
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_page_last);
greetings =(TextView)findViewById(R.id.greetings);
greetings.setText(greeting_message);
}
}
It won't send you back to last acitivity
Intent intent = new Intent(MainActivity.this, WelcomePageLast.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP);
setName("username", input1.getText().toString());
startActivity(intent);
finish();
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) - Clears the activity stack. If you don't want to clear the activity stack. PLease don't use that flag then.
Excuse my ignorance but I was trying to show an interstitial ad while user clicks on multiple button. I have four buttons and each lead to different activity. How can I show same ad (without creating extra ad units & variables) on multiple button click? Here is what I've done so far:
Button btn1, btn2, btn3, btn4;
interstitialAd.setAdListener(new AdListener()
{
#Override
public void onAdClosed() {
super.onAdClosed();
Intent intent = new Intent(MainActivity.this, Activity1.class);
startActivity(intent);
}
}
);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (interstitialAd.isLoaded()) {
interstitialAd.show();
} else {
Intent intent = new Intent(MainActivity.this, Activity1.class);
startActivity(intent);
}
}});
Use onAdClosed method in Interstitial listener to loadAd again if it's already shown and put show funtion on click listeners of the button. I thought four buttons are in the same activity (correct me if I'm wrong)
In your button's onClickListener you used if else statements like show Ads or Go to this activity I mean if unable to show ads then go to this activity, well if the ad was shown to the user then the user will stay at the same activity.
Try this :
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (interstitialAd.isLoaded()) {
interstitialAd.show();
Intent intent = new Intent(MainActivity.this, Activity1.class);
startActivity(intent);
//***This is simple, when the button was clicked Ad will show, also the Activity1 will open.
} else {
Intent intent = new Intent(MainActivity.this, Activity1.class);
startActivity(intent);
}
}});
or You should add Interstitial Listener inside the Click listener method of the button, so you can open another activity when Ad was closed.
You can create a instance of OnClickListener like
OnClickListener onClickListener=new OnClickListener() {
#Override
public void onClick(View view) {
if (interstitialAd.isLoaded()) {
interstitialAd.show();
} else {
Intent intent = new Intent(MainActivity.this, Activity1.class);
startActivity(intent);
}
}
and assign this all button clicks like
btn1.setOnClickListener(onClickListener);
btn2.setOnClickListener(onClickListener);
onButttonClick show ad like Ratish said
OnClickListener onClickListener=new OnClickListener() {
#Override
public void onClick(View view) {
position = 1(for first activity)
if (interstitialAd.isLoaded()) {
interstitialAd.show();
} else{
nextActivity();
}
}
then on Ad closed do go to next activity do this :
make a String array and store all package names in it and declare an int like :
String optionSelected[] = {"com.sb.android.acg.upgrade.activity.firstActivity", "com.sb.android.acg.upgrade.activity.SecondActivity", "com.sb.android.acg.upgrade.activity.ThirdActivity", "com.sb.android.acg.upgrade.activity.FourthActivity", "com.sb.android.acg.upgrade.activity.fifthActivity", "com.sb.android.acg.upgrade.activity.SixthActivity"};
int position
and in onAdClosed:
#Override
public void onAdClosed() {
super.onAdClosed();
nextActivity();
}
and in nextActivity
public void nextActivity(){
Intent intent;
Class<?> aclass = Class.forName(optionSelected[position]);
intent = new Intent(MainActivity.this, aclass);
startActivity(intent);
}
hope you understood how to call next activity. If any doubt tell me in comment
i have my first activity with two EditText fields with hint's as first name and last name, when ever i go to my second activity and return to my first activity by a widget button the EditText fields in my first activity gets reset.
SIMPLY i want my EditText fields to remain same in my first activity as i re-visit my first activity from my second activity.
MY MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButton1Click(View v)
{
Intent intent = new Intent (this,MainActivity2.class);
startActivity(intent);
}
}
My MainActivity2.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
SOLUTION - i changed my second activity to this. just added reference to my Button and applied an onClickListener with onBackPressed(); code.
setContentView(R.layout.activity_main2);
Button button = (Button)findViewById(R.id.button3); //gave reference of button in second activity
button.setOnClickListener(new View.OnClickListener() { //and applied an onClickListener with code onBackpressed();
public void onClick(View v) {
onBackPressed();
// Code here executes on main thread after user presses button
}
});
}
Really Really thnx to #Narendra Sorathiya for his guidance.
Open secondActivity like below,
Intent i = new Intent(A.this,B.class);
startActivity(i);
finish();
to
Intent i = new Intent(A.this,B.class);
startActivityForResult(i,1);
do not open 1st Activity from 2nd Activity, just need to back press.
try this
declare all variavle at top of activity
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String FNAME = "fname";
public static final String LNAME = "lname";
SharedPreferences sharedpreferences;
write this code when you move to your next activity
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// store login data in sharedpreferences
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(FNAME, edittext.getText());
editor.putString(LNAME, edittext2.getText());
editor.commit(); //save data in sharedpreferences
write this code in your oncreate method after you bind your controls
and get data from sharedprefrence like this
String fname= prefs.getString(FNAME, "");
String fname= prefs.getString(LNAME, "");
than set it to your editext like this
editext.setText(fname);
editext2.setText(lname);
let me know in case of any query
Probably something I do not understand.
In the application programs (from google play), if we move from the main activity to the second and then back to the main, then after pressing the "back" button on the phone, the application closes.
I tried to make my own applications with two activities, but it did not work as it should. When the main activity goes to the second and then I go back to the main, then after pressing the "back" button on the phone, the application instead of closing, it goes back to the second activity, then back to the main and it just closes.
What am I doing wrong ?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Act2Butt = (Button) findViewById(R.id.Act2Butt);
Act2Butt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
});
}
.
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button Act1Butt = (Button) findViewById(R.id.Act1Butt);
Act1Butt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main2Activity.this, MainActivity.class );
startActivity(intent);
}
});
}
}
To go back to MainActivity from Main2Activity, you need to call onBackPressed() or finish(), instead of startActivity.