记账本小程序的数据存储实现准备使用xml文件进行存储,xml文件作为轻量级数据的存储个人认为比较适用于家庭记账本的数据存储,而且可以按时间进行存储
今天使用Android开发Android下的学生基本信息管理系统并存储在xml文件.
开发过程中出现这样一个错误
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.StringBuilder java.lang.StringBuilder.append(java.lang.String)‘ on a null object reference
找寻了许多案例最终发现
private StringBuilder newStringBuilder() { // TODO Auto-generated method stub return null; }
在编写该方法的时候少加了一个空行自动生成的方法返回值为NULL了,所以导致了空指针异常的错误。
找到了错误的原因,解决起来便得心应手。
MainActivity源代码展示:
package com.fmd.studentmanager; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.Toast; public class MainActivity extends Activity { private EditText et_name; private EditText et_number; private RadioGroup rg_sex; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_name = findViewById(R.id.et_name); et_number = findViewById(R.id.et_number); rg_sex = findViewById(R.id.rg_sex); } public void save(View view){ String name = et_name.getText().toString().trim(); String number = et_number.getText().toString().trim(); if(TextUtils.isEmpty(name)||TextUtils.isEmpty(number)) { Toast.makeText(this, "学生的姓名或学号不能为空", 0).show(); return; } StringBuilder sb = new StringBuilder(); int id = rg_sex.getCheckedRadioButtonId(); String sex = "male"; if(id == R.id.rb_male) { //男性 sex = "male"; }else { //女性 sex = "female"; } //数据保存到文件 sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); sb.append("<student>"); sb.append("<name>"); sb.append(name); sb.append("</name>"); sb.append("<number>"); sb.append(number); sb.append("</number>"); sb.append("<sex>"); sb.append(sex); sb.append("</sex>"); sb.append("</student>"); try { File file = new File(getFilesDir(),name+".xml"); FileOutputStream fos = new FileOutputStream(file); fos.write(sb.toString().getBytes()); fos.close(); Toast.makeText(this, "数据保存成功", 0).show(); } catch (Exception e) { Toast.makeText(this, "数据保存异常", 0).show(); e.printStackTrace(); } } @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; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
结果展示图: