Patrick260284
Patrick260284

Reputation: 89

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

Upvotes: 0

Views: 48

Answers (2)

Alok
Alok

Reputation: 881

You need call commit() method of shared preference editor after any change in shared preference.. You haven't called this in ondestroy method

Upvotes: 1

Roman Black
Roman Black

Reputation: 3497

It happens because onPostExecute methods executes after onDestroy of Activity and preferences didn't saved. You need to save preferences in onPostExecute method too

Upvotes: 1

Related Questions