简体   繁体   中英

how to get value of switch button from secondActivity?

In my project i have 2 activity , in second activity i have a switch button .

i have 2 problems :

1: I want to get the value of switch button from second activity and pass it to first activity by using shared preferences to show a toast in first activity but i do not get the value of switch button so toast does not work correctly .

2:When i press back or close application , the value of switch button change to default , how can i save the value of switch button ?

This is my first activity :

 public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    Boolean isChecked = settings.getBoolean("status" , false);

    if (isChecked){
        Toast.makeText(this, "Enabled", Toast.LENGTH_SHORT).show();
    }else {
        Toast.makeText(this, "Disabled", Toast.LENGTH_SHORT).show();
    }


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.action_setting:
            Intent settingIntent = new Intent(getApplicationContext(), Main2Activity.class);
            startActivity(settingIntent);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

}

And this is my second activity :

 public class Main2Activity extends AppCompatActivity {

Switch aSwitch;
EditText editText;
Button back;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    editText = (EditText) findViewById(R.id.editText);
    aSwitch = (Switch) findViewById(R.id.switch1);



    back = (Button) findViewById(R.id.btnBack);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent swIntent = new Intent(Main2Activity.this, MainActivity.class);
            startActivity(swIntent);
        }
    });

}

@Override
public void onBackPressed() {
    super.onBackPressed();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putBoolean("MySwitch", true);
    super.onSaveInstanceState(outState);
}

public void enable_disable(View view) {
    if (aSwitch.isChecked()) {

        SharedPreferences.Editor editor = getSharedPreferences("switch", MODE_PRIVATE).edit();
        editor.putBoolean("status", true);
        editor.commit();
    } else {
        SharedPreferences.Editor editor = getSharedPreferences("switch", MODE_PRIVATE).edit();
        editor.putBoolean("status", false);
        editor.commit();
    }
}

}

And this is the layout of my second activity :

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_centerInParent="true"
android:gravity="center"
tools:context="a.switchtest.Main2Activity">



<Switch
    android:id="@+id/switch1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="enable_disable"
    android:text="Switch" />

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<Button
    android:id="@+id/btnBack"
    android:text="Back"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

SharedPreferences are just key value xml files stored on the device. The problem you are having is that you are using two different SharedPreferences which is why the value is not showing up.

In your SecondActivity where you use the line:

getSharedPreferences("switch", MODE_PRIVATE).edit();

You are creating a SharedPreferences file called switch.xml and storing the value of your switch in it. However in your MainActivity when you call:

PreferenceManager.getDefaultSharedPreferences(this);

This fetches the 'default file' which is a different xml file and as such the value is not there. You need to be consistent with which SharedPreferences file you are accessing between the two Activities. In this case I'd recommend just using the default file and changing your SecondActivity to be:

SharedPreferences.Editor editor = PreferenceManager
    .getDefaultSharedPreferences(this)
    .edit();

editor.putBoolean("status", true);
editor.commit();

Now the value will be saved in the default file which is the same one which your reading in the MainActivity

Use switch onChangedListener. This will retain your switch state in your Main2Activity

public class Main2Activity extends AppCompatActivity {

Switch aSwitch;
Button back;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    aSwitch = (Switch) findViewById(R.id.switch1);
    SharedPreferences sharedPreference = getSharedPreferences("switch", MODE_PRIVATE);
    boolean isChecked = sharedPreference.getBoolean("status",false);
    Log.d("Shriyansh",isChecked+"");
    aSwitch.setChecked(isChecked);
    aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // do something, the isChecked will be
            // true if the switch is in the On position
            SharedPreferences.Editor editor = getSharedPreferences("switch", MODE_PRIVATE).edit();
            editor.putBoolean("status", isChecked);
            editor.commit();
            Log.d("Shriyansh1",isChecked+"");
        }
    });

    back = (Button) findViewById(R.id.btnBack);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent swIntent = new Intent(Main2Activity.this, MainActivity.class);
            startActivity(swIntent);
        }
    });

}

Now to show toast in your first activity you can use this preference in onResume() method of your MainActivity

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onResume() {
    super.onResume();
    SharedPreferences sharedPreference = getSharedPreferences("switch", MODE_PRIVATE);
    boolean isChecked = sharedPreference.getBoolean("status",false);
    if (isChecked){
        Toast.makeText(this, "Enabled", Toast.LENGTH_SHORT).show();
    }else {
        Toast.makeText(this, "Disabled", Toast.LENGTH_SHORT).show();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
    case R.id.action_setting:
        Intent settingIntent = new Intent(getApplicationContext(), 
               Main2Activity.class);
        startActivity(settingIntent);
        return true;
    }
    return super.onOptionsItemSelected(item);
 }
}

Layout of your Main2Activity remove enable_disable method for switch

<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_centerInParent="true"
android:gravity="center"
tools:context="a.switchtest.Main2Activity">



<Switch
    android:id="@+id/switch1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Switch" />

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<Button
    android:id="@+id/btnBack"
    android:text="Back"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

in you MainActivity you need to replace

PreferenceManager.getDefaultSharedPreferences(this);

with

SharedPreferences sharedPreference = getSharedPreferences("switch", MODE_PRIVATE);

also remove this from your Main2Activity

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putBoolean("MySwitch", true);
    super.onSaveInstanceState(outState);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM