[英]This android code causes my app to crash
I am new to android development using Java, and I came to how to save application data in SharedPreferences class .. 我是使用Java进行android开发的新手,我来了如何将应用程序数据保存在SharedPreferences类中。
When trying to make this attempt, the app crashs .. 尝试进行此尝试时,应用程序崩溃..
This android java code causes the app to crash when trying to save the data 尝试保存数据时,此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();
}
}
Can anybody help me telling why does this code crash ? 有人可以帮助我告诉我为什么此代码崩溃吗?
you can try this, 你可以试试看
instead of this: 代替这个:
ed.putString("Data", (String) tv.getText());
you can use: 您可以使用:
ed.putString("Data", tv.getText().toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.