how to kill Activity permanetly After button click Using Shared prefrance - android

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

Related

Togglebutton state with shared preferences not changable via asynctask

Ok I have a togglebutton in my main activity. I want the state of this button to be saved if I switch to another activity, minimize the app and a service should be able to set the button state to false (not clicked). Everything worked fine, but for some reason when I started Android Studio again it didnĀ“t work anymore?!
MainActivity:
monitor = (ToggleButton)findViewById(R.id.toggleButton);
monitor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (monitor.isChecked()) {
Intent intent = new Intent(MainActivity.this, NotifiyService.class);
startService(intent);
} else {
Intent intent = new Intent(MainActivity.this, NotifiyService.class);
stopService(intent);
}
}
});
In the onStop Method the following is executed:
if (monitor.isChecked())
{
tbstate = true;
SharedPreferences sharedPreferences1 = getSharedPreferences("tbstate",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences1.edit();
editor.putBoolean("keyTB",tbstate);
editor.commit();
}
else
{
tbstate = false;
SharedPreferences sharedPreferences1 = getSharedPreferences("tbstate",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences1.edit();
editor.putBoolean("keyTB",tbstate);
editor.commit();
}
The onStart Method:
//get Togglebutton state
SharedPreferences sharedPreferences6 = getSharedPreferences("tbstate", MODE_PRIVATE);
monitor.setChecked(sharedPreferences6.getBoolean("keyTB",false));
Asynctask (not complete). In the onPostExecute I set the tbstate to false and in onDestroy it is saved in the sharedpreference. Then a message pop ups which "leads" to main2activity of the same app. When I go from main2activity to mainactivity the togglebutton is still activated.
I hope it is clear what I want ;-)
#Override
public void onDestroy() {
//super.onDestroy();
Th1.interrupt();
checkhttp.cancel(false);
SharedPreferences sharedPreferences8 = getSharedPreferences("tbstate",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences8.edit();
editor.putBoolean("keyTB", tbstate);
Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStopped), Toast.LENGTH_LONG).show();
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
private static class HttpTaskParams{
boolean value;
String address;
HttpTaskParams(boolean value, String address){
this.value = value;
this.address = address;
}
}
private class HttpTask extends AsyncTask<HttpTaskParams,Void,Boolean>{
#Override
protected Boolean doInBackground(HttpTaskParams... params) {
boolean value = params[0].value;
String address = params[0].address;
try {
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
httpURLConnection.connect();
value = true;
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
value = false;
return value;
} catch (IOException e) {
e.printStackTrace();
value = false;
return value;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
//Notification in Status Bar
NotificationCompat.Builder builder = new NotificationCompat.Builder(NotifiyService.this);
builder.setSmallIcon(R.drawable.dummy);
Intent intent = new Intent(NotifiyService.this, Main2Activity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(NotifiyService.this,0,intent,0);
builder.setContentIntent(pendingIntent);
builder.setLights(Color.YELLOW, 600, 600);
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.dummy));
builder.setContentTitle(getResources().getString(R.string.newNotify));
builder.setContentText(getResources().getString(R.string.newNotify2));
builder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
tbstate=false;
onDestroy();
}
}
}
You need call commit() method of shared preference editor after any change in shared preference..
You haven't called this in ondestroy method
It happens because onPostExecute methods executes after onDestroy of Activity and preferences didn't saved. You need to save preferences in onPostExecute method too

SharedPreference cannot save data across activities

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...

Personalization in Android App (Beginner)

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...)

how to save toggle button state to database and if user edits then edited state should be saved to database in android

how to save toggle button state to database and if user edits then edited state should be saved to database in android.the following is my code it is working fine.but the problem is that when user edits to on it is in on state and green light displays on toggle button. and then user performs the required actions.when user again comes back to edit again it displays on only but no green light is visible.so it looks bad so please help me and following is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_layout);
edittext=(EditText)findViewById(R.id.device_text);
light=(ToggleButton)findViewById(R.id.light);
alarm=(ToggleButton)findViewById(R.id.alarm);
db = new DataBaseAdapter(this);
Intent i = getIntent();
if(i.hasExtra("Dname"))
val = i.getStringExtra("Dname");
if(i.hasExtra("Dlight"))
slight=i.getStringExtra("Dlight");
blight=Boolean.valueOf(slight);
if(i.hasExtra("Dalarm"))
salarm=i.getStringExtra("Dalarm");
balarm=Boolean.valueOf(balarm);
if(i.hasExtra("Daddress"))
pos=i.getStringExtra("Daddress");
db.open();
db.insertData(pos,val,slight,salarm);
c = db.getData();
edittext.setText(val);
light.setText(slight);
// light.setChecked(blight);
alarm.setText(salarm);
//alarm.setChecked(balarm);
db.close();
}
#Override
public void onBackPressed(){
db.open();
c=db.getData();
if (c.moveToFirst()) {
do {
String strSQL = "UPDATE DeviceDetails SET devicename ='"+ edittext.getText().toString() +"' WHERE uuid = '"+c.getString(c.getColumnIndex("uuid"))+"'" ;
db.select(strSQL);
slight=light.getText().toString();
salarm=alarm.getText().toString();
if(pos.equalsIgnoreCase(c.getString(c.getColumnIndex("uuid"))))
{
db.updateData(pos, edittext.getText().toString(),slight,salarm);
}
Intent intent=new Intent();
intent.putExtra("Dname", edittext.getText().toString());
intent.putExtra("Daddress",pos);
intent.putExtra("Dlight", slight);
intent.putExtra("Dalarm", salarm);
setResult(RESULT_OK, intent);
finish();
} while (c.moveToNext());
}
db.close();
super.onBackPressed();
}
}
You can use SharedPrefernce for saving the state of toggle button.
sharedpreferences = context.getSharedPreferences("Toggle_pref", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putInt("button_state", "state");
editor.commit();
This is code for Toogle Button with saved state..
private SharedPreferences spref;
private ToggleButton tb;
private boolean on;
spref = getSharedPreferences("APP", MODE_PRIVATE);
tb = (ToggleButton) findViewById(R.id.toogleButton);
on = spref.getBoolean("On", true); //default is true
if (on)
{
tb.setChecked(true);
} else
{
tb.setChecked(false);
}
tb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (tb.isChecked()) {
//Toast.makeText(MainActivity.this, "On : Notification will be Enabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", true); // value to store
editor.commit();
} else {
// Toast.makeText(MainActivity.this, "Off : Notification will be Disabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor =spref.edit();
editor.putBoolean("On", false); // value to store
editor.commit();
}
}
});
in the following way i done and my problem solved.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_layout);
edittext=(EditText)findViewById(R.id.device_text);
light=(ToggleButton)findViewById(R.id.light);
alarm=(ToggleButton)findViewById(R.id.alarm);
db = new DataBaseAdapter(this);
Intent i = getIntent();
if(i.hasExtra("Dname"))
val = i.getStringExtra("Dname");
if(i.hasExtra("Dlight"))
slight=i.getStringExtra("Dlight");
blight=Boolean.valueOf(slight);
if(i.hasExtra("Dalarm"))
salarm=i.getStringExtra("Dalarm");
balarm=Boolean.valueOf(balarm);
Log.v("___EDIT CLASS____________", "__LIGHT TEXT_____________"+slight);
Log.v("_____EDIT CLASS_____________", "___ALARM TEXT____________"+salarm);
Log.v("___EDIT CLASS____________", "__LIGHT boolean_____________"+blight);
Log.v("_____EDIT CLASS_____________", "___ALARM boolean____________"+balarm);
// edittext.setText(val);
if(i.hasExtra("Daddress"))
pos=i.getStringExtra("Daddress");
Log.v("___________edittext", "_______________"+edittext.getText());
Log.v("__________address", "_______________"+pos);
db.open();
db.insertData(pos,val,slight,salarm);
c = db.getData();
edittext.setText(val);
light.setText(slight);
// light.setChecked(blight);
alarm.setText(salarm);
//alarm.setChecked(balarm);
if(slight.equalsIgnoreCase("on"))
{
light.setChecked(true);
}
else
{
light.setChecked(false);
}
if(salarm.equalsIgnoreCase("on"))
{
alarm.setChecked(true);
}
else
{
alarm.setChecked(false);
}
db.close();
}
#Override
public void onBackPressed(){
//saveData();
db.open();
c=db.getData();
if (c.moveToFirst()) {
do {
// slight=light.setClickable(true);
//salarm= String.valueOf(balarm);
Log.v("_______BACK PRESSED", "______UUID___________"+c.getString(c.getColumnIndex("uuid")));
Log.v("_______pos", "______UUID___________"+pos);
String strSQL = "UPDATE DeviceDetails SET devicename ='"+ edittext.getText().toString() +"' WHERE uuid = '"+c.getString(c.getColumnIndex("uuid"))+"'" ;
db.select(strSQL);
Log.v("___QUERY ", "_________________"+db.select(strSQL));
slight=light.getText().toString();
salarm=alarm.getText().toString();
Log.v("___EDIT CLASS____________", "__SLIGHT ___AFTER__________"+slight);
Log.v("_____EDIT CLASS_____________", "___SALARM ___AFTER_________"+salarm);
if(pos.equalsIgnoreCase(c.getString(c.getColumnIndex("uuid"))))
{
db.updateData(pos, edittext.getText().toString(),slight,salarm);
}
/*Log.v("_______BACK PRESSED", "______UUID___________"+c.getString(c.getColumnIndex("uuid")));
Log.v("_______cccccc", "______devicename___________"+c.getString(c.getColumnIndex("devicename")));
Log.v("______EDIT IN DB", "______LIGHT___________"+c.getString(c.getColumnIndex("light")));
Log.v("______EDIT IN DB", "______ALARM___________"+c.getString(c.getColumnIndex("alarm")));
*/
/* Log.v("______device_____text", "_______________"+c.getString(c.getColumnIndex("devicename")));
Log.v("___________edittext", "_______________"+edittext.getText().toString());
Log.v("_____ADDRESS______edittext", "_______________"+pos);
*/ Intent intent=new Intent();
intent.putExtra("Dname", edittext.getText().toString());
Log.v("_____edittext in intent________", "__________"+edittext.getText().toString());
intent.putExtra("Daddress",pos);
Log.v("_____edittext in intent________", "__________"+pos);
intent.putExtra("Dlight", slight);
intent.putExtra("Dalarm", salarm);
setResult(RESULT_OK, intent);
finish();
/* Log.v("_______EDIT IN DB", "______devicename___________"+c.getString(c.getColumnIndex("devicename")));
Log.v("______EDIT IN DB", "______LIGHT___________"+c.getString(c.getColumnIndex("light")));
Log.v("______EDIT IN DB", "______ALARM___________"+c.getString(c.getColumnIndex("alarm")));
*/
} while (c.moveToNext());
}
db.close();
super.onBackPressed();
}

Checkbox Preference and Checking if its enabled or disable

Im having issues with the below code on making a checkbox preference, That by default is checked. My first activity is a simple splash screen, and simply before show my imageview thread i want to check if the checkbox has been disable if so then i want to intent directly to the main activity and by default i show my image thread, or in reversed order of that.
Currently my splashscreen is launching no matter if its checked or now, Any help would be greatly appreciated
XML
<CheckBoxPreference
android:title="#string/category_tools_startupscreen"
android:summary="#string/category_tools_startupscreen_summary"
android:key="boot_animation" android:order="5" android:enabled="true"/>
SplashScreen
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("boot_animation", true)) {
setContentView(R.layout.splash_screen);
Thread splashThread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// changed from 5000 to 4000 11.29
while (waited < 3000) {
sleep(100);
waited += 100;
}
} catch (InterruptedException e) {
// do nothing
} finally {
Intent i = new Intent();
i.setClassName("com.example.app",
"com.example.app.MainActivity");
startActivity(i);
finish();
}
}
};
splashThread.start();
}
else {
Intent i = new Intent();
i.setClassName("com.example.app",
"com.example.app.MainActivity");
startActivity(i);
finish();
}
}
Settings
final CheckBoxPreference checkboxPref2 = (CheckBoxPreference) getPreferenceManager().findPreference("boot_animation");
checkboxPref2.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue instanceof Boolean){
Boolean boolVal = (Boolean)newValue;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("checked", boolVal);
editor.commit();
}
return true;
}
});
In your splash screen
PreferenceManager.setDefaultValues(this, R.xml.your_setting_xml, false);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getBoolean("boot_animation", true)) {
.........
You do not even need the code you posted for the Settings

Categories

Resources