Having more than one Launcher Activity - android

I'm working on an App which can read out car data.
When the user opens it the first time he must choose the car he drives (this is in MainActivity).
What I want to do is, that the user must not always choose his car when opening the App.
The App should directly go to the car data Activity of his car after the user chose the car once.
Can you please give me some ideas how to do that?
I already wrote in the AndroidManifest that MainActivity and this Car Data Activity are Launcher Activities but I think it will not work because how should the App know which Activity should be launch Activity.
Please help me a bit!

You can use SharedPreference for this process.
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(YourLaunchActivity.this);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("isCarSet", true);
editor.apply();
Then Check Everytime Launch activity
if (sharedpreferences.getBoolean("isCarSet", false)) {
Intent i =new Intent(YourLaunchActivity.this,SecondActivty.class);
startActivity(i);
finish();
}
I will suggest you use Shared Preference.

So what you can do in this case is that you can use Shared Preferences. Once the data is registered in Shared Preference, every time the app is started read the data from Shared Preference and go directly to the desired page.
Sample code for Shared Preference:
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
more help at: https://developer.android.com/guide/topics/data/data-storage#pref
The other way around is to use sessions, but being at a nascent stage, I would suggest you to use Shared Preference.

You should create two activities:
- MainActivity (marked as launcher activity in manifest) where you show car data.
- CarChooseActivity where you choose car.
In MainAcitivity on onResume() method try to read car data (from SharedPreferences or other source). If this succeeded then show you car data, otherwise open CarChooseActivity.
Something like that:
public class MainActivity extends AppCompatActivity {
//code omitted
#Override
protected void onResume() {
super.onResume();
Car car = readCar();
if (car == null){//no car saved
Intent i = new Intent(this, CarChooseActivity.class);
startActivity(i);
}
}
//code omitted
}
public class CarChooseActivity extends AppCompatActivity {
Button mSaveButton;
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
//code omitted
mSaveButton = findViewById(R.id.savebutton);
mSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveCar();//save choosed car to SharedPreferences or other storage
finish();
}
});
//code omitted
}
}

Related

How can I get the name of the previous activity and store in a variable

I'm developing an app where I have many activites. And when the user ends interacting with the content of each activity it launchs an Activity called WellDone! where the user can see the average of the lessons (it's a course). 100% completed and it has a button for the next lesson. I want to get the name of the previous activities for example activity_lesson1, activity_lesson2 to show in a TextView to have a Title.
When ends the lesson1 it launchs the WellDone! Activity and I want to set in a TextView (title) the name of the lessons that have just learned.
package com.flixarts.ar.**;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class welldone extends AppCompatActivity {
private TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pantallanextsesion);
title = (TextView)findViewById(R.id.tituloActivity);
title.setText() //Here the title of the previous activity that have come from intent
}
}
My impression is that the answer to the literal question is "no" - you cannot get the name of previous activity. But there's probably another way to accomplish what you need.
If these are all your activities, why not put an extra in the Intent (when going in the forward direction) which says which activity it is coming from.
You can then decide what name of the activity to display based on checking that extra, which should tell you what the previous activity was.
Maybe you could use SharedPreferences, which allow you to easily save some String value in one activity and read it in another. In previous activity e.g activity_lesson1 you could override method onPause (or onDestroy if you finish your activity while proceeding to next one by calling finish() method) and save the name of activity as String like this:
#Override
public void onPause() {
super.onPause();
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("LAST_ACTIVITY_NAME", this.getClass().getSimpleName());
editor.apply();
}
Then you can read saved value inside WellDone activity like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String lastActivityName = sharedPref.getString("LAST_ACTIVITY_NAME", "default_value");
title.setText(lastActivityName);
}
Two ways to pass previous activity name
Use Intent
FirstActivity
String TAG=FirstActivity.class.getSimpleName();
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name=nameEt.getText().toString();
mobile_number=mobileEt.getText().toString();
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("Last_Activity_Name",TAG);
startActivity(intent);
}
});
SecondActivity
String lastActivityName;
lastActivityName=getIntent().getStringExtra("Last_Activity_Name");
**use SharedPreferences **
FirstActivity
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Last_Activity_Name", TAG);
editor.apply();
SecondActivity
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String lastActivityName = sharedPref.getString("Last_Activity_Name",
"default_value");
title.setText(lastActivityName);

Google signin - Need to permanently save user details on exit

I have integrated Google sign in sample application with my applications Main Activity.
I have a button in my Navigation header to launch login activity.
When I login with my google account, it fetches my name and email Id into Navigation Header.
Now the issue is, if I quit this app, I need to sign in again every time. How can I save the login details.
I have gone through multiple articles which talk about Shared Preference, however shared preference doesn't work for me.
Below is one of the code snippet I have tried. I am calling storeUserDetails() in onBackPressed and getUserDetails() in onCreate().
public void storeUserDetails(String userName, String emailID){
mSharedPreference = getSharedPreferences("userDetails",MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreference.edit();
mEditor.putString("userFullName",userName);
mEditor.putString("userEmailID",emailID);
mEditor.apply();
}
private String getUserDetails(){
mSharedPreference = getSharedPreferences("userDetails",MODE_PRIVATE);
return mSharedPreference.getString("userFullName","#gmail.com");
}
Tried this tutorial as well
https://www.tutorialspoint.com/android/android_shared_preferences.htm
//First instantiate sharedpreferences
SharedPreferences sharedpreferences;
sharedpreferences=getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
private String name,phone,email;
//OnPause method to save shared preferences when activity is destroyed
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, name);
editor.putString(Phone, phone);
editor.putString(Email, email);
editor.commit();
}
//OnResume method used to retrieve sharedpreferences
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
SharedPreferences prefs = this.getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
name = prefs.getString("Name","");
phone = prefs.getString("Phone","");
email = prefs.getString("Email","");
}
Also to handle the login issue, you could use your launcher activity and sharedpreferences to check if Name is null, if it isn't then navigate to your mainactivity, and if it is then navigate to login, then on your logout function just make sure you clear the sharedpreferences.

Checking if Shared Preferences Exist

Trying to check if if Shared Preferences exist or not. What I need is to allow the user to arrive on a page if they have been here before (i.e. shared preferences exist and are not equal to "") or put them to the welcome page if it is their first time on the app (i.e. shared preferences are blank as user hasn't entered any data).
public class PersonalDetails extends Activity {
private SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal_details);
if (sharedPreferences.contains("")) {
Intent intent = new Intent(PersonalDetails.this, Welcome.class);
startActivity(intent);
}
I think getPreferences needs two inputs as below.
public abstract SharedPreferences getSharedPreferences(String name,
int mode);
// Example
getSharedPreferences("your_app_name", MODE_PRIVATE);

android using shared preferences issue

static int existingCounter;
Context mContext = SplashScreen.getContextOfApplication();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
public static int cCounter()
{
MainMenu mm = new MainMenu();
existingCounter = mm.getExistingCounter();;
return existingCounter;
}
public void setSharedPreferences(int count)
{
SharedPreferences preferences = mContext.getApplicationContext().getSharedPreferences("myCounter", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("existingCount", existingCounter);
editor.commit();
}
//Get value from shared preferences
public int getExistingCounter()
{
SharedPreferences myPrefs = mContext.getApplicationContext().getSharedPreferences("myCounter", 0);
myPrefs.getInt("existingCount", 0);
return existingCounter ;
}
Hi all, above is my shared preferences. What I am trying to achieve is when user 1st launch the app, my app shall direct user to the disclaimer page and after the user agree to the T&C then in future the user launch the app shall not show the disclaimer page again. However, my current codes only valid when user never exit app. If the user were to exit the app and relaunch, my app still shows the disclaimer page. Please assist =) Thank you in advance. Below is the part where I set the sharedpreferences:
case 3:
cCounter();
if(existingCounter==0)
{
changeMenuFrag(new AcknowledgePg());
existingCounter++;
setSharedPreferences(existingCounter);
}
else
{
changeMenuFrag(new GalleryMain());
}
break;
Save a flag in the Preferences when you start up the application, after you've done the welcome screen stuff. Check for this flag before you show the T&C screen. If the flag is present (in other words, if it's not the first time), don't show it. Instead of a integer counter use a boolean flag and in your main activity check if the flag is true or false based on that show the appropriate activity.
SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// second argument is the default to use if the preference can't be found
Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);
if (!welcomeScreenShown) {
// here you can launch another activity if you like
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit(); // Very important to save the preference}
}

how to pass extra intent to two activities

i have an app that on the first activity asks the persons name on the second page it displays the name in a sentence i want to use the name in the third fourth or 9th activity how do i properly declare it (public?) and call it when and where ever i need it? this is my code sending it
Main
public class MainActivity extends Activity {
Button ok;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.editText);
Typeface font_a = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
name.setTypeface(font_a);
ok=(Button)findViewById(R.id.button);
Typefacefont_b=Typeface.createFromAsset(getAssets(),
"fonts/SignPaintersGothicShaded.ttf");
ok.setTypeface(font_b);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("NAMEDATA",nameStr);
startActivity(intent);
}
});
}
and this is activity 2 receiving it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
String n = this.getIntent().getStringExtra("NAMEDATA");
t.setText(n);
so please how would i reuse this?
Use SharedPreferences to save the name or whatever variable you need, then read whenever you need it. First, create global in MainActivity which will be used as preference file name:
public static final String PREFS_NAME = "MyPrefsFile";
Then, to save:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", name);
editor.commit();
to load:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String name = settings.getString("name", "John");
Once saved, the prefs are accessible for every activity.
So in your case, save the name when ok button is pressed:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", nameStr);
editor.commit();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
});
Then read it:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String n = settings.getString("name", "defaultName");
t.setText(n);
You can do similarly in every activity you need it. See docs here.
You have a number of different approaches to share data between activities. I would say which one you use depends on the ultimate source and destination of the data.
Pass through intents - This is the method you are currently using. To proceed, just keep passing the name to the next intent.
Save to SharedPreference - This method you save the information to the "preference" file of the application. This is useful if the the user is setting up a profile or other semi-fixed information.
Write it to a DB - Here you would create a a new SQLite table for user information and write new rows to it for the name, password, and other info. This has way more overhead and is really only useful if you have multiple users in the same application
Save to a singleton - In this case you create a static class with public properties that can be set. This would be least favorable all the information is lost on application close, but could be useful for temporary creation and retention across many activities. Be warned: bad programming can make singletons a nightmare
Create class extending from Application class.
Implement setter and getter inside that class like,
public class GlobalClass extends Application {
//create setters and getters here
public void setUserInfo(String userInfo) {
}
public void getUserInfo() {
return userInfo;
}
}
then you can use this from any activity like,
GlobalClass app = (GlobalClass ) getApplication();
app.getUserInfo();

Categories

Resources