my problem is this:
I make a toast "welcome" in the Activity Main for the first time that you open the home, and it's ok,but when another page to return to the home via the back button, how can I make the toast "welcome" does not appear anymore?
the code of main activity is:
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
MyActivity actvi1;
int cont=0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnabout=(Button)findViewById(R.id.about);
//click
btnabout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// definisco l'intenzione di aprire l'Activity "aboutme.java"
Intent aboutmejava= new Intent(MyActivity.this,aboutme.class);
startActivity(aboutmejava);
}
}
);
//toast
Toast toast = Toast.makeText(getApplicationContext(),
"Welcome", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 20, 0);
toast.show();
code of aboutme.java
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutme);
Button btnback=(Button)findViewById(R.id.scritta);
btnback.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent main = new Intent(aboutme.this,MyActivity.class);
startActivity(main);
If you want it to only show the very first time the application runs, put a boolean flag in SharedPreferences and check here. There are tons of examples but here is one
If you want it to show *every time the Activity is first run when the app starts, simply replace your onClick() code with onBackPressed(). This way it won't start a new instance of your MyActivity and since the Toast code is in onCreate() and not onResume(), it won't run when you go back by clicking the back button.
SharedPreferences
This works.
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
int show = sp.getInt("firstlaunch", 0);
if(show == 0) {
Toast.makeText(getApplicationContext(), "WELCOME", Toast.LENGTH_LONG).show();
sp.edit().putInt("firstlaunch", 1).apply();
}
Place it in your home activities onCreate method.'
A shared preference is a "setting" of sort. It's a xml file that is loaded which contains all of your settings. When we first run "sp.getInt" you can see that i have a 0 after the "key - fistlaunch". The 0 is specifying what to give our Int SHOW if it can't find any shared preference with that key. Next if the int show is equal to 0 we run our Toast and then change the shared preference value to 1 so next time you run it doesn't show...
boolean b = false;
if(!b) {
Toast toast = Toast.makeText(getApplicationContext(),
"Welcome", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 20, 0);
toast.show();
b = true
}
kind of like that?
Are you another instance of MainActivity?
In order to return to your Main activity you should send an Intent with the flag FLAG_ACTIVITY_CLEAR_TOP (or set android:launchMode="singleTop" in launchMode in AndroidManifest.xml)
Intent main = new Intent(aboutme.this,MyActivity.class);
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
By doing so, your main activity will be restored, instead of creating a new instance of MainActivity
Related
I'm looking for a solution to press the (non-personalized ads) button of the ActivityPolicies and close the MainActivity and then reopen the MainActivity with the correct ad.
MainActivity(principal)
public void politicas(View view) // button
{
Intent i = new Intent (this, ActivityPolicies.class);
i.putExtra("valor","politicas");
startActivity(i);
}
ActivityPolicies
public void NonPersonalizedAdvertising(View view) //button
{
SharedPreferences myPreferences = PreferenceManager.getDefaultSharedPreferences(MensajePoliticas.this);
SharedPreferences.Editor myEditor =myPreferences.edit();
myEditor.putString("POLITICAS","LEIDO_NOACEPTADO");
myEditor.commit();
//Missing some option to close the main activity
*
*
*
//Reopen the main activity
Intent entrar=new Intent(this,MainActivity.class);
startActivity(entrar);
finish(); // Close the current activity (ActivityPolicies)
}
The goal is to close the MainActivity to reload the correct personalized or non-personalized ad. I already have the code but I am missing this option to reload the MainActivity.
Another question:
Close the main activity to reload the ads, can I have problems with some Admob rule?
Thank you very much
If your MainActivity is in backstack, you can call same activity like this:
Intent entrar = new Intent(this,MainActivity.class);
entrar.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // this will open the same MainActivity instance and also give you a new intent.
startActivity(entrar);
Now in your MainActivity you can override onNewIntent
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// here you will get the new Intent. You can reload only the ads programmatically or just call `this.recreate();`
}
I have an activity that has edit text and you can type your name in it, and when you click Save button you will be redirected to MainActivity, but I don't want to open MainActivity by Intent, I make that save button save your name with shared prefs and everything works fine but I don't want to open my Main in Intent I want that when I clicked on save button the current activity that saves data close and previous activity open.
sorry for my bad English.
this is my code for save button
submitButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == submitButt.getId()) {
String name = inputName.getText().toString().trim();
if (isValidInput(name)) {
Intent setint = new Intent(SettingsActivity.this, MainActivity.class);
setint.putExtra("name", name);
saveData();
startActivity(setint);
Toast.makeText(SettingsActivity.this, "Settings Saved", Toast.LENGTH_SHORT).show();
}
}
}
Then you just open the PreviousActivity instead of the MainActivity. Add a checker inside the PreviousActivity if "name" has data or not. You can also use finish(); this will kill the activity.
** Update **
In your MainActivity, let's say you have TextView name. Add:
#Override
public void onResume(){
super.onResume();
// Check your variable if it has value or none
textViewName.setText(variableForSharedPref)
}
Then you can proceed with usual process to go in Settings and Go Back to MainActivity.
I have a main_activity in which by pressing a button I launch a form to be completed:
popup= getLayoutInflater().inflate(R.layout.pop_up, null);
signup = new SignUp(popup);
register = (Button) findViewById(R.id.sign_up);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MyLocalBartender.this);
alertBuilder.setView(popup);
final AlertDialog dialog = alertBuilder.create();
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
dialog.show();
}
});
By what you can see I'm using a second activity class (SignUp) to manage the form and not the root class from which it was launched (main_activity).
In this new class I set all the click listeners etc to verify the inputs through a third class that implements an OnClickListener.
Everything works fine until this point. But now I want to test the page/activity called HomePage in which the user should land to if the form is filled.
So what I don know is I remove the click listener from the previous handler and I create an anonymous one to simply open the new activity on register button pressed:
// signup_registerButton.setOnClickListener(new SignupListener(signup_emailField,signup_passwordField1,
// signup_passwordField2, signup_textTemp,signup_organiserRadio, signup_staffRadio,signup_alertMessage));
////*************************TEST******************* START
signup_registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu = new Intent(getApplicationContext(), HomePage.class);
startActivity(menu);
}
});
////*************************TEST******************* END
but this returns a NullPointerException.
I've tried to launch the HomePage.class from the main_activity directly and it works and also I've tried to launch the main activity from this REGISTER button, which didn't work, so this tells me that the problem it is somewhere here.
You need to pass an Activity Context to the Intent constructor. Activities context and Applications context are not the same. Activities context hold much more inforamtions.
In your case you can do like this:
signup_registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu = new Intent(yourActivity, HomePage.class);
startActivity(menu);
}
});
where yourActivity is your activity instance. You can pass it as variable or access it via main_activity.this from inner classes (Listeners) on anywhere inside your class.
I'm having trouble adding a Button to save text input in my editorActivity class, which is an Activity I designated to view, edit, and save a note item.
The class uses the back button (hardware) and app launcher icon to save the key/value pair to a SharedPreferences object. I want to add a Button that will do the same.
I get an error in the console stating:
res\layout\activity_note_editor.xml:18: error: Error: No resource found that matches the given name (at 'text' with value '#string/Save').
I'm not sure what this implies. And would appreciate some guidance as to where I should to fix this error.
This is what I have so far:
private NoteItem note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_editor); // Load custom note edit layout
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Launcher icon becomes an options button = home
Intent intent = this.getIntent(); // Reference to intent object in first activity
note = new NoteItem();
note.setKey(intent.getStringExtra("key")); // retrieve key and saved in note object
note.setText(intent.getStringExtra("text")); // Retrieve text and save in note object
EditText et = (EditText) findViewById(R.id.noteText);
et.setText(note.getText());
et.setSelection(note.getText().length());
}
private void saveAndFinish() {
EditText et = (EditText) findViewById(R.id.noteText);
String noteText = et.getText().toString();
Intent intent = new Intent();
intent.putExtra("key", note.getKey());
intent.putExtra("text", noteText);
setResult(RESULT_OK, intent);
finish();
}
#Override // launcher icon sends data back to main activity
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
saveAndFinish();
}
return false;
}
#Override // device back button sends data back to main activity
public void onBackPressed() {
saveAndFinish();
}
public void addListenerOnButton(){
Button button = (Button) findViewById(R.id.save);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
saveAndFinish();
}
});
}
}
I'm not sure what this implies.
It implies that you don't have a resource in your strings.xml with the identifier of "Save"
When you use #String, or #anyAndroidResource for that matter, it looks in the corresponding file. So #drawable would look inside the drawables folder for whatever identifier you used.
In values/strings.xml you should have something like
<string name="Save">Save</string>
Resources Docs
Resources Overview Docs
I have three activities: First, Second and Third. I used this method in Second activity:
public void onBackPressed() {
super.onBackPressed();
finish();
}
and this on Third activity:
public void onBackPressed() {
super.onBackPressed();
Intent i = new Intent(Third.this, Second.class);
startActivity(i);
finish();
}
The problem is when I press back button after coming from the Third activity, I am going into First activity instead of finish(). I am successfully exiting the application when I click back button right after coming from first activity but not after coming from Third activity.
How to solve this problem?
EDIT: Thanks for the answers guys,the answer of "Ved Prakash" solved the problem for me.But i have a weird problem now.When i press back button the app is successfully exiting but the app which i minimized to Recent Apps button is coming on to the screen and exiting.For example,if i have opened Setting app before opening my app,when i press back button,my app is exiting and immediately Settings app is also opening and exiting itself.What might be the problem?
Your problem is that you don't seem to understand how Activities work. The finish() function ends the current Activity, and then you receive the previous Activity from the backstack.
My recommendation is that you should use a single Activity, and hold Fragments inside it. If you want it so that pressing the Back button ends the application at any screen that is displayed, you could do the following:
Activity XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/initial_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Activity that holds the Fragments:
public class InitialActivity extends FragmentActivity implements ReplaceWith
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_initial);
getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener()
{
public void onBackStackChanged()
{
int backCount = getSupportFragmentManager().getBackStackEntryCount();
if (backCount == 0)
{
finish();
}
}
});
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.initial_container, new FirstFragment()).commit();
}
}
#Override
public void replaceWith(Fragment fragment)
{
getSupportFragmentManager().beginTransaction().replace(R.id.initial_container, fragment).commit();
}
}
Example for a Fragment:
public class FirstFragment extends Fragment implements View.OnClickListener
{
private ReplaceWith activity_replaceWith;
private ImageView exampleImage;
public FirstFragment()
{
super();
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
activity_replaceWith = (ReplaceWith) activity;
}
catch (ClassCastException e)
{
Log.e(getClass().getSimpleName(), "Activity of " + getClass().getSimpleName() + "must implement ReplaceWith interface!", e);
throw e;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
exampleImage = (ImageView) rootView.findViewById(R.id.fragment_first_example_image);
exampleImage.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v)
{
if(v == exampleImage)
{
activity_replaceWith.replaceWith(new SecondFragment());
//please note that this should be done only if you are planning
//only on single-screen applications
//with no other layouts based on orientation or size
//otherwise, the Activity needs to be responsible for this, not the Fragment
}
}
}
This way, when you press the Back button, your application would end from any displayed screen.
Ok your code is wrong.
If you will look at activity source, you see that activity.onBackPressed() is calling finish(). So if call super.onBackPressed() you don't need to call finish.
Finish() is not stopping your application, it's stopping current activity.
Your code on third activity very strange. You are trying to stop activity and start another same activity.
What exactly you want to achieve?
If you want to exit application from your third activity, you need to clear your backstack. But I think you have problem with structure of your app.
Ok. then you should finish your first activity when you go to second activity like this(If you are using intent for that):
Intent it=new Intent(FirstActivity.this,SecondActivity.class);
finish();
startactivity(it);
and same for Second Activity:
Intent it=new Intent(SecondActivity.this,ThirdActivity.class);
finish();
startactivity(it);
this done your work...when you are in third activity the above activities are finished..
and when you press backButton you will be exit from application..
Good luck.
You can use -
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.
And here is how -
When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "MainActivity".
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
This explanation part is also introduced at exit-an-android-app.