SharedPreference - 怎么样?

时间:2018-06-13 15:59:33

标签: android android-intent sharedpreferences

我创建了启动器活动,其中用户将提供详细信息,例如名字,姓氏,联系人和电子邮件。单击按钮,我希望它存储在共享首选项文件中,然后转到下一个活动。但在这种情况下不会发生这种情况。另一项活动甚至没有开始。然而,如果我编写用于在共享首选项文件中编写的代码并且仅将意图内容保留在onclick函数中,即在我的情况下进行测试,那么它将开始另一个活动。为什么会这样?

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    EditText e1,e2,e3,e4;
    SharedPreferences sp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sp=getSharedPreferences("myuser", Context.MODE_PRIVATE);
        EditText e1=(EditText)findViewById(R.id.t1);
        EditText e2=(EditText)findViewById(R.id.t2);
        EditText e3=(EditText)findViewById(R.id.t3);
        EditText e4=(EditText)findViewById(R.id.t4);
        if(sp.contains("fname"))
        {
            e1.setText(sp.getString("fname",""));
        }
        if(sp.contains("lname"))
        {
            e2.setText(sp.getString("lname",""));
        }
        if(sp.contains("email"))
        {
            e3.setText(sp.getString("email",""));
        }

        if(sp.contains("contact"))
        {
            e4.setText(sp.getString("contact",""));
        }

    }
    public void test(View v)
    {   String f=e1.getText().toString();
        String l=e2.getText().toString();
        String em=e3.getText().toString();
        String c=e4.getText().toString();
        SharedPreferences.Editor ed=sp.edit();
        ed.putString("fname",f);
        ed.putString("lname",l);
        ed.putString("email",em);
        ed.putString("contact",c);
        ed.commit();
        Intent i=new Intent(this,Act2.class);
        startActivity(i);
    }
}

2 个答案:

答案 0 :(得分:0)

设置onClickListener(),应该像。

Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
  @Override public void onClick(View view) {
    test(view);
  }
});

答案 1 :(得分:0)

在你的代码中,你创建了每个编辑文本的两个对象。一个在onCreate中,另一个在onCreate之外。

您正在从外部编辑文本中获取未编译的值,并且您正在另一个editText中使用setText ....

请检查应该只有一个的对象。

相关问题