gpt4 book ai didi

java - 如何修复这个共享首选项?

转载 作者:行者123 更新时间:2023-12-01 10:07:08 24 4
gpt4 key购买 nike

这只是一个简单的练习,但我需要一些有关 SharedPreferences 的帮助。为什么它不起作用。

这是我的 java 类。

public class MainActivity extends AppCompatActivity {
private Button display;
private EditText name;
private TextView text;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences file = getSharedPreferences("lol", MODE_PRIVATE);
final SharedPreferences.Editor editor = file.edit();
display = (Button)findViewById(R.id.display);
text = (TextView) findViewById(R.id.texttext);
display.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
String kk = name.getText().toString().trim();
editor.putString("username ", kk);
editor.commit();
text.setText(
file.getString("username","")
);
}
}
);
}
}

这是catlog,我不明白这个异常。有人可以帮我解释一下吗?

FATAL EXCEPTION: main
Process: com.example.jinyu.practice, PID: 4573
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.jinyu.practice.MainActivity$1.onClick(MainActivity.java:28)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

最佳答案

启动此操作:私有(private) EditText 名称;

类似这样的事情:

setContentView(R.layout.activity_main); //after this
name = (EditText)findViewById(R.id.edit_text);

关于java - 如何修复这个共享首选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36368680/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com