I am new at Android. And I have to design an app where user can input his/her own profile in the app. What i would like to happen is that after the user install the app, the user will be redirected to the ProfileActivityUI to input his/her profile. After that, he/she will be redirected to MainMenuActivityUI of the app.
My problem is that after user input his/her profile info on the app and that when he/she close the app and start the app again, he/she will be redirected to ProfileActivityUI again (in which he/she shouldn't be cause he/she already inputted his/her profile). It should that the user will be redirected to MainMenuActivityUI.
ProfileActivityUI should appear one time only. and that is after installation. But when the user open the app again. it shouldn't appear anymore.
I need your help. cause i dont know how to do that. Sample codes are appreciated. thank you.
hey you need to implement share preference:-
1) on ProfileActivityUI you need to check share preference on load,
SharedPreferences sref;
SharedPreferences.Editor editor;
sref = PreferenceManager.getDefaultSharedPreferences(this);
editor = sref.edit();
String checkstring = sref.getString("RoleID",null);
if(!checkstring==null)
{
Intent i = new intent (this,MainMenuActivityUI.class)
startactivity(i);
}
2)when you ProfileActivityUI is submint successfully then right down this code:-
SharedPreferences sref;
SharedPreferences.Editor editor;
sref = PreferenceManager.getDefaultSharedPreferences(this);
editor = sref.edit();
editor.putString("RoleID", RoleID);
editor.commit();
Intent i = new Intent(this,MainMenuActivityUI.class);
startActivity(i);
finish();
then you get what you want 100%
you should try it with sharedpreferences .
public class ProfileActivityUI extends Activity {
SharedPreferences srefforsignout,sref;
Editor edtr;
int signoutcod;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sref=getSharedPreferences("SignOut", MODE_PRIVATE);
signoutcod=sre.getInt("signoutcode", 0);
if(signoutcod==1){
Intent i=new Intent(getApplicationContext(), MainMenuActivityUI.class);
startActivity(i);
finish();
}
srefforsignout=getSharedPreferences("SignOut", MODE_PRIVATE);
edtr=srefforsignout.edit();
buttonsignin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(ProfileActivityUI.this,MainMenuActivityUI.class);
edtr.putInt("signoutcode", 1);
edtr.commit();
startActivity(i);
});
}
}
I think SharedPreferences will solve your problem try to do this.
First of all make a start up screen (Splash screen) so you can check in background that is user registered or not.
public class SplashScreen extends Activity {
Thread td;
public static final String MyPREFERENCES = "MyPrefs";
String name, pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
td = new Thread(new Runnable() {
#SuppressWarnings("static-access")
#Override
public void run() {
// TODO Auto-generated method stub
try {
td.sleep(3000);
SharedPreferences sharepPreferences = getSharedPreferences(
MyPREFERENCES, Context.MODE_PRIVATE);
//Make sure You have entered same key in my case "email" or "password"..
name = sharepPreferences.getString("email", null);
pass = sharepPreferences.getString("password", null);
if (name == null) {
if (pass == null) {
Intent i = new Intent(SplashScreen.this,
ProfileActivityUI.class);
startActivity(i);
}
} else {
Intent i1 = new Intent(SplashScreen.this,
MainMenuActivityUI.class);
startActivity(i1);
}
finish();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
td.start();
}
Now Whenever user starts your application after installing it, there will be no data in shared preference, so it will be redirected to ProfileActivityUI.
Now in ProfileActivityUI you have to save data which user has entered in SharedPreferences.
Do this in your ProfileActivityUI
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs"; //Make sure this is same in both activity.
sharedPreferences = getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", et1.getText().toString());
editor.putString("password", et4.getText().toString());
editor.commit();
This will Store your data permanently.
Now if you open your Application again it will redirect you to the ProfileActivityUI straight after splash screen.
What I would do is to start in the MainMenuActivityUI and if the profile it's not saved , automatically redirects him to the ProfileActivityUI.
If the UI it's not very complicated you always can make a setContentView for one or the other view (but it's kind of messy thing...)
Related
So I'm trying to save a value to sharedpreferences by a click of a button, and then see which value it is in another activity. (to basically set a background for activity2 based on which button they pressed in activity1)
Saving code:
public void onClick(View v) {
SharedPreferences.Editor background = getSharedPreferences("Background", MODE_PRIVATE).edit();
if(btn1 == v)
{
background.remove("selectedBG");
Toast.makeText(this, "btn1", Toast.LENGTH_SHORT).show();
background.putInt("selectedBG", 1);
background.commit();
}
if(btn2 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 2);
Toast.makeText(this, "btn2", Toast.LENGTH_SHORT).show();
background.commit();
}
if(btn3 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 3);
Toast.makeText(this, "btn3", Toast.LENGTH_SHORT).show();
background.commit();
}
if(btn4 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 4);
Toast.makeText(this, "btn4", Toast.LENGTH_SHORT).show();
background.commit();
}
}
And then, the Toast here always shows "chosenbackground:0":
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
LLayout=(LinearLayout)findViewById(R.id.llayout);
SharedPreferences background2 = getSharedPreferences("Background", MODE_PRIVATE);
int chosenBackground = background2.getInt("selectedBg", 0);
Toast.makeText(this,"chosenBackground:" + chosenBackground, Toast.LENGTH_SHORT).show();
if (chosenBackground != 0) {
if(chosenBackground==1)
{
LLayout.setBackgroundColor(Color.WHITE);
}
if(chosenBackground==2)
{
LLayout.setBackgroundColor(Color.rgb(34,34,34));
}
if(chosenBackground==3)
{
LLayout.setBackgroundColor(Color.rgb(51,68,85));
}
if(chosenBackground==4)
{
LLayout.setBackgroundColor(Color.rgb(68,34,17));
}
}
}
Answer for your question is that you have misspelled the key in second activity, in first one you are using "selectedBG" but in the second one "selectedBg". It is not the same, it's case sensitive. Correct in the second one for "selectedBG" and it should work.
Using the SharedPreferences here it's really bad idea, if u only want to pass a background or rather a color if I see it correctly. Just pass it in intent:
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("EXTRA_BACKGROUND_ID", background);
startActivity(intent);
Access that intent on next activity for eg. in onCreate()
String s = getIntent().getStringExtra("EXTRA_SESSION_ID");
#Updated
public class PreferencesUtils {
private SharedPreferences sharedPrefs;
private SharedPreferences.Editor prefsEditor;
public static final String KEY_BACKGROUND = "BACKGROUND";
public PreferencesUtils(Context context) {
this(context, PREFS_DEFAULT);
}
public PreferencesUtils(Context context, String prefs) {
this.sharedPrefs = context.getSharedPreferences(prefs, Activity.MODE_PRIVATE);
this.prefsEditor = sharedPrefs.edit();
}
public int getValue(String key, int defaultValue){
return sharedPrefs.getInt(key, defaultValue);
}
public boolean saveValue(String key, int value){
prefsEditor.putInt(key, value);
return prefsEditor.commit();
}
}
PreferencesUtils preferencesUtils = new PreferencesUtils(this);
preferencesUtils.saveValue(PreferencesUtils.KEY_BACKGROUND, 1); //saveValue
preferencesUtils.getValue(PreferencesUtils.KEY_BACKGROUND, 0); //getValue,
second arg is defult if not found
Use if (!background2.contains("selectedBg"))
to check ,first whether the key exists and if not getInt is not able to create a key and hence always returns default value 0.Also you can use apply() instead of commit to check whether commit has taken place successfully.Debug the code more to see all possibilities
int chosenBackground=0;
if (!background2.contains("selectedBg"))
{
//is called once when after you freshly install the app
background2.putInt("selectedBG", 0);
}
else
chosenBackground = background2.getInt("selectedBg", 0);
I have RegisterPage and LoginPage. When the app is run, it will check whether the app is first time run or not in RegisterPage. If it is first time run and the save button is not clicked, it will in RegisterPage. If it is run second times but the save button is never clicked, it will remain in RegisterPage too. Otherwise it will go to LoginPage.
Here my updated code
Register
appGetFirstTimeRun();
boolean clicked=false;
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked=true;
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
appPreferences.edit().putInt("app_second_time",
appCurrentBuildVersion).apply();
String name = editTextName.getText().toString();
String pass = editTextPassword.getText().toString();
String confirm = editTextConfirm.getText().toString();
if ((editTextName.getText().toString().trim().length() == 0) || (editTextPassword.getText().toString().trim().length() == 0) || (editTextConfirm.getText().toString().trim().length() == 0)) {
Toast.makeText(getApplicationContext(), "Field cannot be null", Toast.LENGTH_LONG).show();
}
else
{
insertData(name, pass, imageUri); // insert to SQLite
Intent intent = new Intent(MainActivity.this, AddMonthlyExpenses.class);
intent.putExtra("name", name);
startActivity(intent);
}
}
});
private int appGetFirstTimeRun() {
//Check if App Start First Time
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
int appLastBuildVersion = appPreferences.getInt("app_first_time", 0);
if (appLastBuildVersion == appCurrentBuildVersion && clicked) {
Intent intent = new Intent(MainActivity.this,LoginPage.class);
startActivity(intent);
return 1;
} else {
appPreferences.edit().putInt("app_first_time",
appCurrentBuildVersion).apply();
if (appLastBuildVersion == 0) {
Toast.makeText(getApplicationContext(), "First time", Toast.LENGTH_SHORT).show();
return 0; //es la primera vez
} else {
return 2; //es una versión nueva
}
}
}
The problem is when I click the save button and exit from the app. When I run the app again it still in the RegisterPage, not in LoginPage.
Check button click after inserting data into SQLite, So you can confirm that your data has successfully saved and you can proceed to next screen.
Find my comments in below code and edit your code:-
public class Register extends AppCompatActivity {
Button buttonSave;
boolean clicked=false;//remove this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
appGetFirstTimeRun();//call this method here
buttonSave=(Button)findViewById(R.id.button);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked=true;//remove this
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
appPreferences.edit().putInt("app_second_time", appCurrentBuildVersion).apply();
String name = editTextName.getText().toString();
String pass = editTextPassword.getText().toString();
String confirm = editTextConfirm.getText().toString();
if ((editTextName.getText().toString().trim().length() == 0) || (editTextPassword.getText().toString().trim().length() == 0) || (editTextConfirm.getText().toString().trim().length() == 0)) {
Toast.makeText(getApplicationContext(), "Field cannot be null", Toast.LENGTH_LONG).show();
}
else
{
insertData(name, pass, imageUri); // insert to SQLite
appPreferences.edit().putBoolean("btn_clicked", true).apply();//add this line
Intent intent = new Intent(Register.this, AddMonthlyExpenses.class);
intent.putExtra("name", name);
startActivity(intent);
}
}
});
}
private int appGetFirstTimeRun() {
//Check if App Start First Time
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
int appLastBuildVersion = appPreferences.getInt("app_first_time", 0);
boolean is_btn_click=appPreferences.getBoolean("btn_clicked",false);//add this line
if ((appLastBuildVersion == appCurrentBuildVersion) && is_btn_click) { //edit this line like this
Intent intent = new Intent(Register.this,LoginPage.class);
startActivity(intent);
return 1;
} else {
appPreferences.edit().putInt("app_first_time",
appCurrentBuildVersion).apply();
if (appLastBuildVersion == 0) {
Toast.makeText(getApplicationContext(), "First time", Toast.LENGTH_SHORT).show();
return 0; //es la primera vez
} else {
return 2; //es una versión nueva
}
}
}
}
you are depending on SharedPreferences as well as on clicked variable, you can depend on SharePreferences but not on variable because on each run you are setting clicked value to false.
1) Save current version in preference when button is clicked
appPreferences.edit().putInt("app_first_time",
appCurrentBuildVersion).apply();
2) save clicked value in preference when button is clicked
appPreferences.edit().putBoolean("clicked",
true).apply();
Now inside your appGetFirstTimeRun() fetch the value of version and clicked from SharedPreferences
int appLastBuildVersion = appPreferences.getInt("app_first_time", 0);
boolean clicked = appPreferences.getBoolean("clicked", false);
You also need to change the shared preferences value on click of save button. Then only next time when you open the app appGetFirstTimeRun method will load the Login page.
In you btnSave click listener where you are starting intent for activity just before startActivity add this code
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
appPreferences.edit().putInt("app_first_time",
appCurrentBuildVersion).apply();
in start of onCreate(); method, call checkStages();
in end of buttonSave.onClick() method, call Prefs.putStage(this, 1); followed by checkStages();
/*Prefs.getStage(this) default value is 0*/
public void checkStages() {
switch(Prefs.getStage(this)) {
case 1: //Login Page
startActivity(new Intent(this, LoginPage.class));
finish();
break;
default:
break;
}
}
This is the sample Android Application Template I use, to write any of my Android App.
You can get the Prefs class from this project
add this code to your splash screen
SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(context);
boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", false);
if (!isFirstRun) {
startActivity(new Intent(context,RegirstorActivity.class));
}else{
startActivity(new Intent(context,LoginActivty.class));
}
so basically it will decide Is it first time (user registered) or not, after registration update the SharedPreferences
your are using click variable to identify if button is clicked or not but when you exist from the app and again then click value reset to false so instead of saving value in click variable you can use shared preference to save value true or false on button click and get value from shared preference to check
on click of save button
appPreferences.edit().putInt("app_second_time",
appCurrentBuildVersion).apply();
Try using following custom getter and setter method.
private static SharedPreferences getInstance(Context context) {
context.getSharedPreferences("MY_APP", Context.MODE_PRIVATE);
return sharedPreferences;
}
public boolean getAppStatus(Context context) {
return getInstance(context).getString("FIRST_TIME", false);
}
public void setAppStatus(Context context, boolean status) {
getInstance(context).edit().putString("FIRST_TIME", status).commit();
}
Now, When for the first time when you call getAppStatus() or in case where user haven't clicked save button even once. It will return false. You can update the value of "FIRST_TIME" variable when the user clicks on save button to true. Thus validating, whether user has interacted with register page or not.
#Override
public void onClick(View v) {
if(v.getId()==R.id.save_button)
setAppStatus(context,true);
}
I think this may be the answer. on your code clicked boolean variable is not stored on shared preferences but you are checking condition inside appGetFirstTimeRun() (button may not be clicked at second launch, but your condition needs to be true) so change your code by
Adding this line appPreferences.edit().putBoolean("first_run", true).apply();on buttonSave clicklistener and then add this line clicked = appPreferences.getBoolean("first_run", false);on appGetFirstTimeRun() function
and the complete code would be.
appGetFirstTimeRun();
boolean clicked=false;
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
appPreferences = appPreferences.edit().putBoolean("first_run",
true).apply(); //***Add this ****
appPreferences.edit().putInt("app_second_time",
appCurrentBuildVersion).apply();
String name = editTextName.getText().toString();
String pass = editTextPassword.getText().toString();
String confirm = editTextConfirm.getText().toString();
if ((editTextName.getText().toString().trim().length() == 0) || (editTextPassword.getText().toString().trim().length() == 0) || (editTextConfirm.getText().toString().trim().length() == 0)) {
Toast.makeText(getApplicationContext(), "Field cannot be null", Toast.LENGTH_LONG).show();
}
else
{
insertData(name, pass, imageUri); // insert to SQLite
Intent intent = new Intent(MainActivity.this, AddMonthlyExpenses.class);
intent.putExtra("name", name);
startActivity(intent);
}
}
});
private int appGetFirstTimeRun() {
//Check if App Start First Time
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
int appLastBuildVersion = appPreferences.getInt("app_first_time", 0);
clicked = appPreferences.getBoolean("first_run", false); //*** Add this ***
if (appLastBuildVersion == appCurrentBuildVersion && clicked) {
Intent intent = new Intent(MainActivity.this,LoginPage.class);
startActivity(intent);
return 1;
} else {
appPreferences.edit().putInt("app_first_time",
appCurrentBuildVersion).apply();
if (appLastBuildVersion == 0) {
Toast.makeText(getApplicationContext(), "First time", Toast.LENGTH_SHORT).show();
return 0; //es la primera vez
} else {
return 2; //es una versión nueva
}
}
}
//Use shared preference to save.
SharedPreferences preferedName=getSharedPreferences("firstrun", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferedName.edit();
editor.putboolean("firstrun",value);
editor.apply();
editor.commit();
//and to retrive.
SharedPreferences preferedName=getSharedPreferences("firstrun", Activity.MODE_PRIVATE);
boolean rstate =preferedName.getString("firstrun",false);
check if "rstste" is false show register page else show the login page.
I'm working on a splash screen where it will determine whether the user has previously registered or not based on SharedPreference stored values.
Please allow me to ask this question one more time, as I've gone through so many help / tutorials and examples, it didn't help a bit. I've been stuck here for 2 days now... Any help is really really appreciated.
There are 2 activities involved. The app starts with SplashScreen activity, then if sharepreference file return non-null (means user registered before), it will start mainactivity. Else if sharepreference file return null (means first time user, it brings user to the registration activity)...
PROBLEM: whenever the app restart (even with user registered), it always go to registration page !! PLEASE HELP !!
code for SPLASHSCREEN activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
Thread timerThread = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
}
}
};
timerThread.start();
}
protected void onStart() {
super.onStart();
openNextActivity();
}
public void openNextActivity(){
SharedPreferences sp = getSharedPreferences("pref", 0);
if (sp.contains("Name")) {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
} else {
Intent intent = new Intent(SplashScreen.this, Registration.class);
startActivity(intent);
}
}
#Override
protected void onPause() {
super.onPause();
finish();
}
below is the code for REGISTRATION activity...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
etMobilePhone = (EditText) findViewById(R.id.etMobilePhone);
tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // imei
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSubmit:
writePref();
break;
}
finish();
}
private void writePref() {
String userName = etName.getText().toString(); //prepare variables values for write
String userPhone = etMobilePhone.getText().toString(); //prepare variables values for write
String userEmail = etEmail.getText().toString(); //prepare variables values for write
String userImei = tel.getDeviceId().toString(); //prepare variables values for write
SharedPreferences sp = getSharedPreferences("pref", 0); //sharepreference
SharedPreferences.Editor editor = sp.edit(); //sharepreference
editor.putString(Name, userName); //write sharepreferences
editor.putString(Phone, userPhone); //write sharepreferences
editor.putString(Email, userEmail); //write sharepreferences
editor.putString(Imei, userImei); //write sharepreferences
editor.commit(); //sharepreference
Toast toast = Toast.makeText(getApplicationContext(), "updated sharepreferences", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,0,50);
toast.show();
}
Please guide me to the right directions. Thank you for reading and responding.
Change your openNextActivity() method to this:
public void openNextActivity(){
SharedPreferences sp = getSharedPreferences("pref", 0);
String defaultValue = "na";
String storedValue = sp.getString("Name", defaultValue);
if (!storedValue.equalsIgnoreCase("na")) {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
} else { //if you get default value i.e. "na"
Intent intent = new Intent(SplashScreen.this, Registration.class);
startActivity(intent);
}
}
Instead of checking if the key exists, check for its value. If key not found return a default value and and check against the returned value.
Update (From Jelle's comment below): Also change your RegistrationActivity. Change editor.putString(Name, userName); into editor.putString("Name", userName);
Thanks guys... wanted to share the solution...
SharedPreferences sp = getSharedPreferences("pref", 0); //sharepreference
SharedPreferences.Editor editor = sp.edit(); //sharepreference
editor.putString("Name", userName); //write sharepreferences
editor.putString("Phone", userPhone); //write sharepreferences
editor.putString("Email", userEmail); //write sharepreferences
editor.putString("Imei", userImei); //write sharepreferences
editor.commit(); //sharepreference
Apparently, the solution is the ""... thanks for all the wonderful people...
public class MainActivity extends Activity {
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent newpage = new Intent(MainActivity.this, PhonrRegistaion.class);
startActivity(newpage);
btn1=(Button)findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myintent=new Intent(MainActivity.this,nextActvity.class);
startActivities(null);
}
});
}
}
this is my Activity i want moving from one Activity to another Activity i want to kill my Activity permanently using shared prefrances means if open Application then it should launch second Activity . please help i dont know how to kill Activity using shred prefrances
here is the complete solution
//firstly when you register the user set the shared preferences in your register class like this
//declare pref editor
SharedPreferences prefs;
SharedPreferences.Editor prefsEditor;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefsEditor = prefs.edit();
//paste below peace of code when the registration will be success
prefsEditor.putString("register", "yes");
prefsEditor.commit();
//now in your first activity you just check the shared pref value to know the user is register or no
SharedPreferences prefs;
String register;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
register=prefs.getString("register", "");
//now check the value of shared pref and apply the condition like this
Intent intent ;
if(register.equalsIgnoreCase("yes"))
{
intent = new Intent(this, NextAct.class);
startActivity(intent);
finish();
}
else
{
intent = new Intent(this, Register.class);
startActivity(intent);
finish();
}
You cannot "kill" an activity but you can finish() it.
In onCreate() create condition:
if (<your condition>) {
startActivity(...);
finish();
}
Either finish the old activity when the new one is started:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = getSharedPreferences(LOC_PREF_FILE, MODE_PRIVATE);
Boolean startSecond = prefs.getBoolean("StartSecondActivty", false);
if (startSecond) {
Intent newpage = new Intent(this, PhonrRegistaion.class);
startActivity(newpage);
finish();
}
btn1=(Button)findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myintent=new Intent(this, nextActvity.class);
startActivities(null);
finish();
SharedPreferences prefs = getSharedPreferences(
LOC_PREF_FILE, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("StartSecondActivty", true);
editor.commit();
editor.apply();
}
});
}
}
This is not permanent as such as it will reside in memory until GC.
If you want to permanently kill you activity (and app) try killing your own process:
// Kill everything you can
public void killMyProcess() {
try {
Process process = Runtime.getRuntime().exec(
"/system/bin/kill -9 -1");
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
process.waitFor();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
I'm trying to loop inside a handler to every 2 seconds to simulate the home button press using a sharedpreference flag isHomeActive. It will try to check for the flag every 2 seconds inside the service whether it is active. If the value is no, it will try to relaunch the application but if it is yes, the application won't be relaunched. I am unable to get the loop working so far
onResume and onPause for main activity:
#Override
public void onPause()
{
super.onPause();
SharedPreferences home = PreferenceManager.getDefaultSharedPreferences(PhysicalTheftDialog.this);
Editor edit=home.edit();
edit.putString("isHomeActive", "no");
edit.commit();
}
#Override
public void onResume()
{
super.onResume();
SharedPreferences home = PreferenceManager.getDefaultSharedPreferences(PhysicalTheftDialog.this);
Editor edit=home.edit();
edit.putString("isHomeActive", "yes");
edit.commit();
}
The loop inside service class:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(PhysicalTheftService.this);
final String isHomeActive = sp.getString("isHomeActive", "");
Runnable myRunnable = new Runnable() {
public void run() {
while (isHomeActive.equals("no")) {
try {
Intent physicaldialog = new Intent(PhysicalTheftService.this, PhysicalTheftDialog.class);
physicaldialog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PhysicalTheftService.this.startActivity(physicaldialog);
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
You are only ever populating isHomeActive one time, so the value will never change. You need to populate it inside the loop.