Android: clear activities stack [duplicate] - java

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.

Related

Sending data to Listview of another activity

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();
}

Pressing the back button goes back to first launched activity

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

how to save EditText's value after performing an other activity

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

How to make onClickListener receive Intent information from another activity

I'm trying to make a button use some data from another activity, I did seach, but I didn't find out how.
The onClickListener doesn't work.
Here is the code inside my onCreate:
super.onCreate(savedInstanceState);
setContentView(R.layout.show_message);
Intent intent = getIntent();
String msg = intent.getStringExtra("MESSAGE");
ScrollTextView scrolltext = (ScrollTextView) findViewById(R.id.scroll_text);
scrolltext.setText(msg);
scrolltext.setTextSize(220);
scrolltext.startScroll();
super.onResume();
DialogFragment mDialog = new GeneralDialogFragment();
mDialog.show(getSupportFragmentManager(), "Dialog TAG");
ImageButton mImageButton = (ImageButton)findViewById(R.id.image_button);
mImageButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//I'm sure this is not the to make this button works. What code should I put here to pass this data to the ScrollTextView?
scrolltext.setText(msg);
scrolltext.setTextSize(220);
scrolltext.startScroll();
}
});
This two lines that you wrote are just used to get information from the previous activity that was executing
Intent intent = getIntent();
String msg = intent.getStringExtra("MESSAGE");
If you want to use data from another activity at any time, you have to save the data in the previous activity with these lines:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("msg", "MESSAGE");
editor.commit();
and call it on your activity like this:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String yourmessage = prefs.getString("msg", null);
if (restoredText != null) {
String name = prefs.getString("msg", "No name defined");//"No name defined" is the default value.
}

sending text from editText to ListView (2 activities)

i am new to Andriod and programming. i am trying to make a to do list app, which will contain a listView, Button(add) in the main layout. when i click add i want it to go to another activity which will contain a editText and a add button. when i click the add button i want to update the list in my main activity. Now i was able to get the information from the second activity but when i try to add it in my list it over writes it.
How can i update my list as soon as my main activity appears again.
Here's what i have so far :
MainActivity class :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
add = (Button) findViewById(R.id.bAdd);
list = (ListView) findViewById(R.id.lvList);
addItems(); // i think this is the error but i dont know how to fix it.
alList = new ArrayList<String>();
aaList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, alList);
list.setAdapter(aaList);
}
public void clickAdd(View v) { //when clicking the add button(add)
Intent intent = new Intent(MainActivity.this, AddItem.class);
startActivity(intent);
}
private void addItems(){
String s = getIntent().getStringExtra("item");
aaList.add(s);
aaList.notifyDataSetChanged();
}
AddItem class :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_layout);
et = (EditText) findViewById(R.id.etAdd);
bt = (Button) findViewById(R.id.badd);
}
public void add(View v){ //when clicking the add button(bt)
edit = et.getText().toString();
Intent intent = new Intent(AddItem.this, MainActivity.class);
intent.putExtra("item", edit);
startActivity(intent);
}
Can you please tell me where and why i am going wrong? Thank You
First of all, you should use startACtivityForResult
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
Then in your second Activity
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
And back in your fist one:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
and then, your addItem should do the trick:
private void addItems(String s){
aaList.add(s);
aaList.notifyDataSetChanged();
}

Categories