0

I am making an app that control light bulb remotely. so i require that app saves automatically the previous state(variables, onlick button, etc) and resume it after i restart the app. For example if i pressed on bulb(in my code it changes picture on click) and picture changes so when i close app and reopen it, the image shown should be changed one.

Here's my code

package room.bt4u.com.roomcontrol;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
public class MainActivity extends AppCompatActivity {
ImageButton ib;
MediaPlayer toggleSound;
ImageButton aButton,aButton2;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toggleSound=MediaPlayer.create(this, R.raw.z);
    aButton = (ImageButton) findViewById(R.id.imageButton);
    aButton2 = (ImageButton) findViewById(R.id.imageButton2);
    SharedPreferences sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
    Boolean c = sharedPreferences.getBoolean("clicked", false);
    Boolean d = sharedPreferences.getBoolean("clicked2",false);

    if(c) {
        aButton.setImageResource(R.drawable.on);
    }
    else {
        aButton.setImageResource(R.drawable.off);

    }
    if(d){

        aButton2.setImageResource(R.drawable.on);
    }
    else {

        aButton2.setImageResource(R.drawable.off);
    }
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}


public void buttonClick(View v) {
    SharedPreferences sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
    Boolean c = sharedPreferences.getBoolean("clicked",false);
    if (!c) {
        aButton.setImageResource(R.drawable.on);
        toggleSound.start();
        sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("clicked", true);
        editor.commit();
    }
    if(c){
        aButton.setImageResource(R.drawable.off);
        sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor = sharedPreferences.edit();
        editor.putBoolean("clicked", false);
        editor.commit();
        toggleSound.start();

    }
}
public void buttonClick2(View v) {
    SharedPreferences sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
    Boolean d = sharedPreferences.getBoolean("clicked",false);
    if (!d) {
        aButton2.setImageResource(R.drawable.on);
        toggleSound.start();
        sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("clicked2", true);
        editor.commit();
    }
    if(d){
        aButton2.setImageResource(R.drawable.off);
        sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor = sharedPreferences.edit();
        editor.putBoolean("clicked2", false);
        editor.commit();
        toggleSound.start();

    }
}

And here's the XML FILE

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="room.bt4u.com.roomcontrol.MainActivity"
android:orientation="vertical">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ROOM NO. 1046"
    android:textSize="45sp"
    android:textStyle="bold"
    android:layout_centerHorizontal="true"
    android:textColor="#0786e7"
    android:id="@+id/textView"
    android:includeFontPadding="false"
   android:gravity="center_horizontal"
    />


<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageButton"
    android:layout_below="@+id/textView"
    android:src="@drawable/off"
    android:layout_marginTop="35dp"
    android:layout_alignParentLeft="true"
    android:background="#01FFFFFF"
    android:onClick="buttonClick"/>

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageButton2"
    android:layout_alignTop="@+id/imageButton"
    android:layout_below="@+id/textView"
    android:src="@drawable/off"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:background="#01FFFFFF"
    android:onClick="buttonClick2"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Swarnveer&apos;s"
    android:id="@+id/textView2"
    android:layout_below="@+id/imageButton"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginLeft="20dp"
    android:textStyle="bold"
    android:textColor="#f20606"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Sajal&apos;s"
    android:id="@+id/textView3"

    android:layout_below="@+id/imageButton2"
    android:layout_alignRight="@+id/imageButton2"
    android:layout_alignEnd="@+id/imageButton2"
    android:layout_marginRight="35dp"
    android:layout_marginEnd="35dp"
    android:textStyle="bold"
    android:textColor="#f20606"/>

</RelativeLayout>
Swarnveer
  • 490
  • 5
  • 23

4 Answers4

1

You can use SharedPreferences:

referring here for the infos: You can use SharedPreferences to save little setting datas on your phone.

In your onPause(), use the following code:

SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
prefs.edit().putString("myKey", "myColorState").apply();

In this way the setting of "myColorState" is saved under the key "myKey".

In onResume() you can retrieve this value using

SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
String myColor = prefs.getString("myKey", "defaultValue"); 

In this way you have your datas and you can use them in the activity

Community
  • 1
  • 1
Pier Giorgio Misley
  • 5,305
  • 4
  • 27
  • 66
1

If you don't have bidirectional communication with the Bulb, saving the states to SharedPreferences seems like the best way to go.

You can retrieve the data from the SharedPreferences in your Activity or Fragment lifecycle Methods (onConfigurationChanged(), onResume(), onStart()).

Check out SharedPreferences here

Flo We
  • 325
  • 2
  • 12
0

you can use SharedPref for saving your data using any key on screen orientation change or on backpress and you can again get that data using this key also.

  • when i press bulb(white) it becomes yellow so if my app gets killed or orientation changes i want the bulb to show yellow automatically without any click – Swarnveer Mar 02 '16 at 09:04
0
    Try this:


        @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            toggleSound= MediaPlayer.create(this, R.raw.z);
            SharedPreferences sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
            Boolean c = sharedPreferences.getBoolean("clicked");
            if(c){
                aButton.setImageResource(R.drawable.on);
            }
            else {
                aButton.setImageResource(R.drawable.off);
            }        
        }


        public void buttonClick(View v) {
            switch (choose){
                case 1:ImageButton aButton = (ImageButton) v;
                    aButton.setImageResource(R.drawable.on);
                    toggleSound.start();
                    choose++;
                    SharedPreferences sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean("clicked", true);
                    editor.commit();
                    break;
                case 2:ImageButton bButton = (ImageButton) v;
                    bButton.setImageResource(R.drawable.off);
SharedPreferences sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean("clicked", false);
                    editor.commit();
                    toggleSound.start();
                    choose--;
                    break;
            }
Khizar Hayat
  • 3,427
  • 3
  • 18
  • 22
  • remove getActvity. i was working on fragment. in activity no need getActivity – Khizar Hayat Mar 02 '16 at 09:41
  • i declare ImageButton aButton; globally – Swarnveer Mar 02 '16 at 09:48
  • also in getBoolean("STRING",false) there should be a true or false it was showing errow so i put default false – Swarnveer Mar 02 '16 at 09:49
  • aButton = findViewById(R.id.YOUBUTTONID) ; paste YOUBUTTONID and put this line below setContentView – Khizar Hayat Mar 02 '16 at 09:50
  • default false is ok. it should be there. – Khizar Hayat Mar 02 '16 at 09:51
  • app is not crashing not crashing now but it's not functioning .. default state now is on(yellow) when clicked state is same ON when clicked another time goes OFF And when restarting app default is showing ON everytime – Swarnveer Mar 02 '16 at 09:55
  • thats because of you variable choose check your logic – Khizar Hayat Mar 02 '16 at 09:57
  • my logic is fine as choose=1 if choose=1, and i click>becomes yellow>choose++ now if clicked choose becomes 2(due to choose++)>sets white>choose-- – Swarnveer Mar 02 '16 at 10:02
  • Now its retaining it's state but if i close it when it is yellow(ON) then next time when i restart it shows yellow(that is ok) but i click to get white(off), it doesn't change with one click i have to press two times – Swarnveer Mar 02 '16 at 10:16
  • used same method for button2 but don't know why it's totally depending upon button 1 – Swarnveer Mar 02 '16 at 10:50
  • done..editted the code Buttonclick is working fine but buttonclick2 not with same logic – Swarnveer Mar 02 '16 at 11:46
  • public void buttonClick2(View v) { SharedPreferences sharedPreferences = getSharedPreferences("NAME", Context.MODE_PRIVATE); Boolean d = sharedPreferences.getBoolean("clicked",false); ... } using clicked in use clicked2 instead – Khizar Hayat Mar 02 '16 at 11:51
  • aah such a silly mistake i did...thanks for supporting that much. you made my day – Swarnveer Mar 02 '16 at 12:07
  • if you can help me on this another question [LINK]http://stackoverflow.com/questions/35772102/usage-of-gif-in-imagebutton?noredirect=1#comment59215863_35772102 that would be great – Swarnveer Mar 03 '16 at 16:56