下面的页面是我想要从用户保存的数据。
如何在具有editText
文本视图的下一个活动中读取此数据?
此代码是否正确?
AddMoney.class
public class AddMoney extends AppCompatActivity {
Button b1;
EditText et;
enter code here
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_money);
b1 = (Button) findViewById(R.id.b1);
et = (EditText) findViewById(R.id.et);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveData();
AlertDialog.Builder b = new AlertDialog.Builder(AddMoney.this);
b.setIcon(R.mipmap.ic_launcher);
int val = Integer.parseInt(et.getText().toString());
b.setTitle("MONEY ADDED");
String msg = "₹" + val + " has been added in your wallet";
b.setMessage(msg);
b.setCancelable(false);
b.setPositiveButton("OK",null);
AlertDialog d = b.create();
d.show();
}
});
}
public void saveData() {
try {
FileOutputStream fileOutputStream = openFileOutput("Expenses.txt", MODE_PRIVATE);
fileOutputStream.write(et.getText().toString().getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
作为一种更好的方法,您可以像SripadRaj建议的那样使用SharedPreference
。
在第一个活动中,您保存数据:
SharedPreference sp =getSharedPreferences("app_package_name", Context.MODE_PRIVATE);
sp.putString("expense",et.getText().toString());
sp.apply();
关于另一项活动:
SharedPreference sp =getSharedPreferences("app_package_name", Context.MODE_PRIVATE);
String expense = sp.getString("expense","0.0");