移动应用开发技术移动应用数据存储.docx
移动应用开发技术移动应用数据存储一、实验目的1 . 了解数据存储的多种方法、数据共享的方法;2 .掌握文件存储技术及具体应用;3 .掌握SQLite数据库存储技术及具体应用。二、实验内容在上次实验设计的“心情日记本”系统的基础上,增加如下功能:1 .保存登录信息在用户登录界面中增加一个复选框“记住姓名”。当勾选了该复选框后,系统的用户登录Activity 将保存最近的一次用户登录信息。2 .保存注册信息在用户注册界面中实现注册按钮的单击事件。当单击注册按钮时,将注册信息保存在文件中(昵 称为自己名字全拼),并用Toast方式将文件中的数据输出。3 .日记查看点击日记按钮进入日记查看页面。在该页面中用ListView显示数据库中存储的每一条日志信息, 具体包括:日志标题、日志的建立或修改时间。如实验2图4所示。4 .保存日志信息在日志编辑页面中单击发布日志按钮时,将当前日志信息保存在数据库中(包括日志标题、创 建或修改时间(获取系统时间)、日志内容)。三、实验步骤1、保存登录信息步骤:新建一个复选框,点击了复选框“记住账号”后,创立一个名为“prefile”的配置文件,然后 将登录的账号保存到文件中。在下一次翻开登陆界面时,将之前存储的账号取出,放到输入框中。代码实现:public class MainActivity extends AppCompatActivity 实现效果:C导入向导EE导出向导V笈选向导IS网格查看兰表单查看:箭主:L 日志 main (11111)-表文件。查看 曹匚 瞽助_id时间内容12021-11-05 09:17:18111111卜|y12021-11-05 09:18:311111113112021-11-05 09:21:3011114 ,保存日志信息在日志编辑页面中单击发布日志按钮时,将当前日志信息保存在数据库中(包括日志标题、创 建或修改时间(获取系统时间)、日志内容)。步骤:先获取SharePreferenced对象,添加键值对的数据,判断是否的是第一次创立数据表,防 止屡次创立数据表。将写在编辑框的内容与系统时间存储在Contentvalues中,同时将内容插入到数 据库中,点击“发表”按钮后跳转回日记显示页面。代码实现:public class DirayActivity extends AppCompatActivity private ImageView back;private EditText content;private EditText title;private Button publish;SQLiteDatabase db;private String time;String title 1 = null;String contentl 二 null;©Overrideprotected void onCreate(Bundle savedlnstanceState) super.onCreate(savedlnstanceState);setContentView(R.layout.activity_diray);back = (ImageView) findViewByld(R.id.back);title = findViewByTd(R.id.title);content = findViewByld(R.id.content);publish = findViewById(R.id.publish);翻开或创立数据库与数据表db 二 openOrCreateDatabase(nDatabase3.dbn, MODE_PRIVATE, null);SharedPreferences sp;sp = this.getSharedPreferences(nconfig4n, MODE_PRIVATE);if (sp.getString(nisfirstn, null) = null) SharedPreferences.Editor editor = sp.edit();editor.putStringC'isfirst",“yes");存入账号editor mit();db.execSQL(MDROP TABLE IF EXISTS 日志”);String sql="CREATE TABLE 日志(Jd INTEGER PRIMARY KEY AUTOINCREMENT, 标题 VARCHAR,时间 VARCHAR,内容 VARCHAR)”;db.execSQL(sql);publish.setOnClickListener(new ClickEvent();back.setOnClickListener(new View.OnClickListener() ©Overridepublic void onClick(View view) Intent intent = new Intent(DirayActivity.this, OptionsMenuActivity.class);startActivity(intent);finishQ;);class ClickEvent implements View.OnClickListener Overridepublic void onClick(View view) title 1 = title.getText().toString();content 1 = content.getText().toString();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssn);time = sdf.format(new Date();Contentvalues cv = new ContentValues();cv.put("标题”,title 1);cv.put("时间”,time);cv.put("内容”,content 1);db.insert("日志”,null, cv);)protected void onStopO super.onStopO;db.closeQ;)实现效果:L 1 日志 main (11111)-表文件 编相 查看 窗匚 帮助导入向导 6导出向导 V标选向导起网格亘看 5表单直看亡 苗注B内容1111111111111111jd标飘时间1yi2021-11-05 09:17:183112021-11-0509:21:30yi2021-11-05 09:18:31四、实验总结通过实验,初步了解了 SQLite的一些基本操作,但在实验3, 4中,一开始点击日记页面,页 面直接崩溃,但代码没有问题,后来发现由于是第一次运行,先执行的是查询数据表操作,导致程 序无法正常运行,最后先把查询局部注释掉,运行一次后,将注释局部还原,再次运行,问题顺利 解决。private Button button 1;private Button button;登录private EditText count;private EditText password;private CheckBox chk;复选框String username二null;String pass=null;String name二null;String passwordR=null;申明简单存储sharedpreferencesprivate SharedPreferences sPreferences;Overrideprotected void onCreate(Bundle savedlnstanceState) super.onCreate(savedlnstanceState);setContentView(R.layout.activity_main);count 二 findViewByld(R.id.count);password=findViewById(R.id.password);button !=(Button)findViewById(R.id.button 1);chk=(CheckBox) GndViewById(R.id.chk);复选框buttonl .setOnClickListener(new View.OnClickListener() Overridepublic void onClick(View v) Intent itl = new Intent(getApplicationContext(),ZhuceActivity.class);/ startActivity(itl);startActivityForResult(itl ,1););button=(Button)findViewById(R.id.button);button.setOnClickListener(new View.OnClickListener() ©Overridepublic void onClick(View v) username=count.getText().toString();pass=password.getText().toString();if (username.isEmpty()|pass.isEmpty()Toast.makeText(getApplicationContext(),n 请输入账号密码 H,Toast.LENGTH_LONG).show();)if (!username.equals(nyuanjien)Toast.makeText(getApplicationContext(),n 账 号 不 正 确 Toast.LENGTH_LONG).show();)if (username.equals(name)&&!pass.equals(passwordR)Toast.makeText(getApplicationContext(), “ 密 码 错 误 ”, Toast.LENGTH_SHORT).show();)if(username.equals(name)&&pass.equals(passwordR)&&!passwordR.isEmpty()&&!name.isEmpty()Toast.makeText(getApplicationContext(),H 登 录 成 功 Toast.LENGTH_LONG).show();Intent intent=new Intent(MainActivity.this,DActivity.class);start Activity (intent);)if (chk.isChecked()Log. i("执行了“,“记住密码)得到简单存储的编辑器SharedPreferences.Editor editor=sPreferences. edit();editor. putStringC'count”,username); 写入账号editor. putString(”passworcT,passwordR); 写入密码editor, commit。;/保存完数据后一定要提交 elseLog. i("执行了 不记住密码));获得简单存储sPreferences=this.getSharedPreferences(nconfig",0);String userl=sPreferences.getString("count”J");得至|账号String pwdl=sPreferences.getString("passworcT,"");得到密码count.setText(userl),将账号写入编辑框password.setText(pwdl);/将密码写入编辑框 Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data)EditText count=findViewById(R.id.count);super.onActivityResult(requestCode, resultCode, data);if(requestCode= 1)if(resultCode=RESULT_OK) name=data.getExtras().getString(ncountH);passwordR=data.getExtras().getString(npasswordn);if (name.equals(nyuanjie,')&&!passwordR.isEmpty()Toast.makeText(getApplicationContext(),n 注 册 成 功 n,Toast.LENGTH_LONG).show(); count.setText(name);elseToast.makeText(getApplicationContext(),nerrorH,Toast.LENGTH_LONG).show();)实现效果:2、保存注册信息tivity d.xml activity main.xml 力 config.xml Q MainActivity.jc ?xml version='1.0' encoding='utf-8' standalone= * yes1 ?> map><string name="password">lll</string><string name="count">yuanjie</string> /map>步骤:注册完成后点击注册按钮,创立写入数据流,生成Buffer流,通过getBytes()方法将账号和密 码的内容转换成byte类型写入文件中,然后关闭Buffer流,并将输入框中的内容清空,跳转到登录 界面后,将账号以Toast方式输出。代码实现:public class ZhuceActivity extends AppCompatActivity private Button button 1;private Button button?;private EditText count;private EditText password;private EditText password 1;private EditText mail;String username=null;String pass=null;String passl=null;Ovemdeprotected void onCreate(Nullable Bundle savedlnstanceState) super.onCreate(savedlnstanceState);setContentView(R.layout.activity_c);button 1 =(Button)findViewById(R.id.zhuce);button2=(Button)findViewById(R.id.fanhui);count=findViewById(R.id.count);password=findViewById(R.id.password);password l=findViewById(R.id.password!);mail=findViewById(R.id.mail);button 1 .setOnClickListener(new View.OnClickListener() Overridepublic void onClick(View v) boolean temp=true;usemame=count.getText().toString();pass=password.getText().toString();pass 1 =password 1 .getText().toString();if (usemame.isEmpty()|pass.isEmpty()|passl.isEmpty()Toast.makeText(ZhuceActivity.this,n 用户名 密码不 能为空 n,Toast.LENGTH_LONG).show();temp=false;)if (! pass.equals(pass 1) Toast.makeText(ZhuceActivity.this,n 输入的 两次密 码不同 n,Toast.LENGTH_LONG).show();temp=false; if(temp) try ( Intent it=new Intent();it.setClass(getApplicationContext(),MainActivity.class);it.putExtra(Hcountn,username);it.putExtra( "password”,pass);setResult(RESUUT_OK,it);finishQ;FileOutputStream fout=openFileOutput(,'text.txt,',MODE_PRIVATE);BufferedOutputStream bufferout=new BufferedOutputStream(fout);FileOutputStream foutl=openFileOutput(ntextl.txtn,MODE_PRIVATE);BufferedOutputStream bufferoutl=new BufferedOutputStream(foutl);FileOutputStream fout2=openFileOutput(,'text2.txt',MODE_PRIVATE);BufferedOutputStream bufferout2=new BufferedOutputStream(fout2);bufferout.write(username.getBytes();bufferoutl.write(pass.getBytes();bufferout2.write(pass l.getBytes();bufferout.close();bufferoutl.close();bufferout2.close();count.setText(nn);password.setText(nn);passwordl.setText(',H);Toast.makeText(getApplicationContext(),n 账 号 n+usemame,Toast.LENGTH_LONG).show();密码确 认 密 码Toast.makeText(getApplicationContext(),n n+pass,Toast.LENGTH_LONG).show();Toast.makeText(getApplicationContext(),n n+passl ,Toast.LENGTH_LONG).show(); catch (Exception ee)ee.printStackTrace(););button2.setOnClickListener(new View.OnClickListener() Overridepublic void onClick(View v) Intent it2=new Intent(ZhuceActivity.this,MainActivity.class);startActivity(it2);finishQ;);实现效果:idroidManifestxmlJi activityd.xmlu activity main.xml| text.txt ,自 text1.txt <123droidManifest.xml -: 曷 activity d.xml 翡 activity main.xml m text.txt yuaniieAndroidManifest.xml . activity d.xml 11 activity main.xml 自 text2.txt3、日记查看点击日记按钮进入日记查看页面。在该页面中用ListView显示数据库中存储的每一条日志信息, 具体包括:日志标题、日志的建立或修改时间。如实验2图4所示口步骤:通过openOrCreateDatabases函数翻开或者创立数据库,然后用查询的SQL语句查询日记 并放到Cursor的集合中,有通过适配器将Cursor与ListView进行映射,最终将数据显示在界面上。代码实现:public class OptionsMenuActivity extends AppCompatActivity private ListView listView;SQLiteDatabase db;Overrideprotected void onCreate(Bundle savedlnstanceState) super.onCreate(savedlnstanceState);setContentView(R.layout.activity_dirayO); initView();private void initView()listView=findViewById(R.id.ListView);db = openOrCreateDatabase(HDatabase3.dbH, MODE_PRIVATE, null);Cursor cursor= db.rawQuery(nselect * from 日 志”,null);if(cursor!=null&&cursor.getCount()>=0) S impleCursorAdapter cursorAdapter=newSimpleCursorAdapter(getApplicationContext(),R.layout.item_diary,cursor,new String口 “标题" J时间 ”,new intR.id.DiaryTitle_item,R.id.DiaryTime_item);listView. setAdapter(cursorAdapter);) (©Override public boolean onCreateOptionsMenu(Menu menu) Menulnflater menulnflater = getMenuInflater(); menuInflater.inflate(R.menu.menu_options,menu); return true;)Overridepublic boolean onOptionsItemSelected(NonNull Menuitem item) int itemld = item.getltemld();switch (itemld) case R.id.add:Intent intent = new Intent(getApplicationContext(), DirayActivity.class);start Activity (intent);return true;case R.id.delete:AlertDialog.Builder builder=new AlertDialog.Builder(this);builder. setTitleC'删除”);设置对话框的标题 builder.setMessage(“你确定要删除吗? ");/设置对话框的内容 builder.setPositiveButton("确定”,null);builder.setNegativeButton("取7肖",null);AlertDialog b=builder.create();b.showQ; /必须show 一下才能看到对话框,跟Toast 一样的道理 return true;default:break;return super.onOptionsItemSelected(item);