我是使用 Java 进行 android 开发的新手,我了解了如何在 SharedPreferences 类中保存应用程序数据..
尝试进行此尝试时,应用程序崩溃..
此 android java 代码导致应用程序在尝试保存数据时崩溃
package com.example.savedata;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
TextView tv;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = getSharedPreferences ("MYFILENAME",MODE_PRIVATE);
tv = (TextView)findViewById(R.id.txtData);
tv.setText(sp.getString("Data","0"));
}
@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;
}
public void saveDate(View v){
sp = getSharedPreferences("MYFILENAME", MODE_PRIVATE);
TextView tv;
SharedPreferences.Editor ed = sp.edit();
tv = (TextView)findViewById(R.id.txtData);
ed.putString("Data", (String) tv.getText());
ed.commit();
}
}
谁能帮我告诉为什么这段代码会崩溃?