使用sharedpreferences android将数据发送到其他活动

时间:2015-09-16 14:44:40

标签: android sharedpreferences

我在互联网上找到了一个教程,用于保存和加载同一活动中相同文本字段的文本。但我想在另一个活动的文本视图中加载一些数据(名称年龄)。我该怎么做

public class MainActivity extends Activity {
    SharedPreferences sharedpreferences;
    TextView name;
    TextView email;// age
    TextView gender;//weight
    TextView height;
    public static final String mypreference = "mypref";
    public static final String Name = "nameKey";
    public static final String Email = "emailKey";
    public static final String Gender = "genderKey";
    public static final String Height = "heightKey";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        gender = (TextView) findViewById(R.id.etGender);
        height = (TextView) findViewById(R.id.etHeight);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);
        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(Email)) {
            email.setText(sharedpreferences.getString(Email, ""));
        }
        if (sharedpreferences.contains(Gender)) {
            gender.setText(sharedpreferences.getString(Gender, ""));
        }
        if (sharedpreferences.contains(Height)) {
            height.setText(sharedpreferences.getString(Height, ""));

        }

    }

    public void Save(View view) {
        String n = name.getText().toString();
        String e = email.getText().toString();
        String g = gender.getText().toString();
        String h = height.getText().toString();
        Editor editor = sharedpreferences.edit();
        editor.putString(Name, n);
        editor.putString(Email, e);
        editor.putString(Gender, g);
        editor.putString(Height, h);
        editor.commit();
    }

    public void clear(View view) {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        gender = (TextView) findViewById(R.id.etGender);
        height = (TextView) findViewById(R.id.etHeight);
        name.setText("");
        email.setText("");
        gender.setText("");
        height.setText("");

    }

    public void Get(View view) {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        gender = (TextView) findViewById(R.id.etGender);
        height = (TextView) findViewById(R.id.etHeight);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(Email)) {
            email.setText(sharedpreferences.getString(Email, ""));
        }
        if (sharedpreferences.contains(Gender)) {
            gender.setText(sharedpreferences.getString(Gender, ""));
        }
        if (sharedpreferences.contains(Height)) {
            height.setText(sharedpreferences.getString(Height, ""));

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

3 个答案:

答案 0 :(得分:2)

用于发送新活动的数据 在主要活动中声明两个变量

public static final String TAG_NAME = "nameKey";
public static final String TAG_AGE = "emailKey";

Intent actt = new Intent(CurrentActivity.this,NewActivity.class);
actt.putExtra(TAG_AGE,age.getText().toString());
actt.putExtra(TAG_NAME,name.getText().toString());
startActivity(actt);

在NewActivity中接收oncreate方法

public class NewActivity extends Activity {

    TextView name;
    TextView age;         

    public static final String TAG_NAME = "nameKey";
    public static final String TAG_AGE = "emailKey";      

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (TextView) findViewById(R.id.name);
        age = (TextView) findViewById(R.id.age);

        String Name=getIntent().getStringExtra(TAG_NAME);
        String Age=getIntent().getStringExtra(TAG_AGE);

        name.setText(Name);
        age.setText(Age);
    }
}

方法2使用sharedpreferances

public class NewActivity extends Activity {
   public static final String mypreference = "mypref";
       TextView name;
       TextView age;            

       public static final String TAG_NAME = "nameKey";
       public static final String TAG_AGE = "emailKey";


       @Override
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
           name = (TextView) findViewById(R.id.name);
           age = (TextView) findViewById(R.id.age);
           sharedpreferences=getSharedPreferences(mypreference,Context.MODE_PRIVATE);
           String Name=sharedpreferences.getString(TAG_NAME,"");
           String Age=sharedpreferences.getString(TAG_AGE,"");

           name.setText(Name);
           age.setText(Age);
        }
}

答案 1 :(得分:0)

您可以将数据传递到用于启动活动的Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.Vector.elementData(Unknown Source) at java.util.Vector.elementAt(Unknown Source) at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source) at Test$1.valueChanged(Test.java:34) at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source) at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source) at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source) at javax.swing.DefaultListSelectionModel.removeIndexInterval(Unknown Source) at javax.swing.JTable.tableRowsDeleted(Unknown Source) at javax.swing.JTable.tableChanged(Unknown Source) at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source) at javax.swing.table.AbstractTableModel.fireTableRowsDeleted(Unknown Source) at javax.swing.table.DefaultTableModel.removeRow(Unknown Source) at Test$2.actionPerformed(Test.java:39) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$500(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) 中的其他活动。

Intent

在其他活动中,您可以通过调用Intent newActivity = new Intent(CurrentActivity.this,OtherActivity.class); newActivity.putExtra(TAG_ADDRESS,<insert address here>); newActivity.putExtra(TAG_NAME,<insert name here>); startActivity(newActivity); 然后Intent来获取getIntent()以获取姓名和地址。

答案 2 :(得分:0)

我认为有两种方法可以做到这一点。

1.按意图传递数据

Intent intent = new Intent(MainActivity.this, OtherActivity.class);
intent.putExtra(TAG_AGE, <insert age here>);
intent.putExtra(TAG_NAME, <insert name here>);
startActivity(intent);

并在OtherActivity的onCreate方法中加载数据:

Intent intent = getIntent();
String age = intent.getStringExtra(TAG_AGE);
String name = intent.getStringExtra(TAG_NAME);
ageTextView.setText(age);
nameTextView.setText(name);

2。通过共享偏好获取数据

由于您已使用整个应用程序共享的共享首选项将数据保存在MainActivity中,因此可以使用以下方法在OtherActivity的onCreate方法中获取数据:

 sharedpreferences = getSharedPreferences(mypreference,
            Context.MODE_PRIVATE);
 nameTextView.setText(sharedpreferences.getString(Name, ""));
 ageTextView.setText(sharedpreferences.getString(Age, ""));

它与您在MainActivity中使用的方式相同。