这只是一种简单的练习,但我需要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)
答案 0 :(得分:1)
发起此:cube.updateMatrix();
geom.merge(cube.geometry, cube.matrix);
这样的事情:
private EditText name;
答案 1 :(得分:0)
Try This
In your source code you are declare the EditText object but you are not
initilise this EditText before you are geting the value using getText()
method so you get this NullPointerException Exception.
change like this
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);
name== (EditText)findViewById(R.id.edit_text);
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","")
);
}
}
);
}
}