Android 应用基础技术3_第1页
Android 应用基础技术3_第2页
Android 应用基础技术3_第3页
Android 应用基础技术3_第4页
Android 应用基础技术3_第5页
已阅读5页,还剩61页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第11章保存程序数据在程序运行过程中,经常需要保存一些程序运行的数据,例如,为了避免用户每次登录时都被要求输入用户名和密码,当用户运行程序首次成功登录系统后,程序会将用户的登录数据保存下来,当用户下次再运行程序时,则不需要再次输入用户名、密码等数据。可以使用Android提供的SharedPreferences来保存程序运行过程中的数据,也可以使用普通文件来保存这些数据,当然,还可以将这些数据保存在SQLite数据库中。目录11.1使用SharedPreferences保存程序数据11.2课堂同步练习11.3程序首选项11.4在应用程序沙箱/家目录下存储数据11.5使用SQLite数据库保存数据11.1使用SharedPreferences保存程序数据SharedPreferences提供了一个基本框架,通过使用SharedPreferences,可以非常方便地将程序运行数据保存下来。想要得到一个SharedPreferences对象,只需要在Activity中,调用getSharedPreferences(Stringname,intmode)或getPreferences(intmode)函数,其中的name参数是指定的用于保存数据的文件名,mode参数设为0即可。getPreferences(intmode)函数只是简单地调用了getSharedPreferences(Stringname,intmode)函数,并设定name参数为固定的值:调用这个函数的Activity的类名而已。下面通过一个简单的例子介绍如何使用SharedPreferences保存程序数据。程序首先显示一个登录界面,提示用户输入用户名和密码,一旦用户点击“登录”按钮,程序会将用户输入的用户名和密码保存下来,当用户再次运行这个程序时,程序会自动地将上次用户输入的用户名和密码填入到相应的输入框中。新建一个名为ch1101的工程。修改res/layout/activity_main.xml文件,修改后的文件内容如下:<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="/apk/res/android"xmlns:app="/apk/res-auto"xmlns:tools="/tools"android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity">

<EditTextandroid:id="@+id/id_et_name"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="@string/text_name"/>

<EditTextandroid:id="@+id/id_et_password"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="textPassword"android:hint="@string/text_password"/>

<LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal">

<Buttonandroid:id="@+id/id_btn_login"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="@string/text_login"/>

<Buttonandroid:id="@+id/id_btn_reset"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="@string/text_reset"/>

</LinearLayout>

</LinearLayout>修改res/values/strings.xml文件,在其中定义布局文件中用到的字符串引用,内容如下:<resources><stringname="app_name">ch1101</string>

<stringname="text_name">用户名</string><stringname="text_password">密码</string><stringname="text_login">登录</string><stringname="text_reset">重置</string>

</resources>修改MainActivity.java文件,使之显示主界面,并处理对按钮的点击事件:一旦用户点击“登录”按钮,则将用户输入的用户名和密码通过SharedPreferences保存下来。修改后的文件内容如下:packagecom.example.ch1101;

importandroid.content.SharedPreferences;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;importandroid.widget.EditText;

importandroidx.activity.EdgeToEdge;importandroidx.appcompat.app.AppCompatActivity;importandroidx.core.graphics.Insets;importandroidx.core.view.ViewCompat;importandroidx.core.view.WindowInsetsCompat;publicclassMainActivityextendsAppCompatActivityimplementsView.OnClickListener{privateEditTextet_name,et_password;

@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_main);ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main),(v,insets)->{InsetssystemBars=insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left,systemBars.top,systemBars.right,systemBars.bottom);returninsets;});

Buttonbtn_login=this.findViewById(R.id.id_btn_login);btn_login.setOnClickListener(this);Buttonbtn_reset=this.findViewById(R.id.id_btn_reset);btn_reset.setOnClickListener(this);

et_name=this.findViewById(R.id.id_et_name);et_password=this.findViewById(R.id.id_et_password);

SharedPreferencessp=this.getSharedPreferences("mimi",0);Stringname=sp.getString("name","");et_name.setText(name);Stringpassword=sp.getString("password","");et_password.setText(password);}

@OverridepublicvoidonClick(Viewv){intid=v.getId();if(id==R.id.id_btn_login){SharedPreferencessp=this.getSharedPreferences("mimi",0);SharedPreferences.Editoreditor=sp.edit();editor.putString("name",et_name.getText().toString());editor.putString("password",et_password.getText().toString());editor.apply();}else{et_name.setText("");et_password.setText("");}}}11.2课堂同步练习完善11.1节的例子,做出如下修改:当用户点击“登录”按钮时,不仅在SharedPreferences中保存用户输入的用户名和密码,同时还保存用户登录的日期和时间。当用户再次运行程序时,不仅将上次用户输入的用户名和密码自动填入到相应输入框中,还通过一个Toast显示上次登录的日期和时间。完成后,运行程序,并使用“DeviceExplorer”观察应用程序的安装目录下文件的变化和文件结构。11.3程序首选项应用程序APP通常会包括一些设置,以便用户可以改变程序的运行特征。例如,设置程序的界面风格、网络的刷新时间间隔或其他的一些与应用程序本身相关的运行参数。为了使Android应用程序与Android自带的“系统设置”应用具有一致的外观,Android提供了一个称为Preference的API。可以使用这个API来构建应用程序的首选项设置。PreferenceAPI提供了首选项设置界面所需的组件,这些首选项组件所设置的值都以“key/value”的方式保存在应用程序安装目录下的shared_prefs子目录下文件名为“程序包名_preferencex.xml”的XML文件中,可以在首选项中保存的值包括Boolean、Float、Int、Long、String及String数组。常用的Preference的组件包括:(1)CheckBoxPreference显示一个复选框用于设置某个特性是否可运行。(2)ListPreference显示一个列表框,并在列表框中显示一组单选按钮,用于选择某个特征。(3)EditTextPreference显示一个输入框,用于输入某个值。下面通过一个例子说明如何设置和使用应用程序首选项:这个例子通过应用程序首选项设置所显示的文字“HelloWorld!”的样式,可设置的首选项包括是否以动画形式显示界面文字、文字的颜色、文字大小、文字的语种(中文或英文)。新建名为ch1102的工程。修改res/layout/activity_main.xml文件,使其显示一个TextView和一个Button按钮。修改后的文件内容如下:<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="/apk/res/android"xmlns:tools="/tools"android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity">

<TextViewandroid:id="@+id/id_textview"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="9"android:gravity="center"android:text="@string/text_hello_world_en"/>

<Buttonandroid:id="@+id/id_btn"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:text="@string/setting"/>

</LinearLayout>为了显示程序首选项设置界面,在res/xml子目录下,新建名为my_settings.xml文件(文件名可以是任意合法的文件名),修改后该文件的内容如下:<?xmlversion="1.0"encoding="utf-8"?><PreferenceScreenxmlns:android="/apk/res/android">

<CheckBoxPreferenceandroid:key="pref_animation"android:title="@string/text_pref_animation"android:summary="@string/text_pref_animation_summ"android:defaultValue="false"/>

<ListPreferenceandroid:key="pref_lang_type"android:title="@string/text_pref_lang_type"android:dialogTitle="@string/text_pref_lang_type"android:entries="@array/pref_lang_type_entries"android:entryValues="@array/pref_lang_type_values"android:defaultValue="1"/>

<PreferenceCategoryandroid:title="@string/text_pref_appearence_title"><EditTextPreferenceandroid:key="pref_text_size"android:title="@string/text_pref_text_size"android:summary="@string/text_pref_text_size_summ"android:defaultValue="16"/><EditTextPreferenceandroid:key="pref_text_color"android:title="@string/text_pref_text_color"android:summary="@string/text_pref_text_color_summ"android:defaultValue="#FF000000"/></PreferenceCategory>

</PreferenceScreen>需要修改res/values/strings.xml文件,在其中定义需要的引用,修改后的文件内容如下:<resources><stringname="app_name">ch1102</string>

<stringname="setting">Settings</string>

<stringname="text_hello_world_en">Helloworld!</string><stringname="text_hello_world_cn">你好,世界!</string>

<stringname="text_pref_animation">以动画形式显示文字</string><stringname="text_pref_animation_summ">

选中该选项,可以以动画的形式显示界面文字</string><stringname="text_pref_lang_type">选择显示文字的语种</string>

<string-arrayname="pref_lang_type_entries"><item>English</item><item>中文</item></string-array>

<string-arrayname="pref_lang_type_values"><item>1</item><item>2</item></string-array>

<stringname="text_pref_appearence_title">设置文字显示的外观</string><stringname="text_pref_text_size">文字字体大小</string><stringname="text_pref_text_size_summ">

文字字体大小,请输入一个数值</string><stringname="text_pref_text_color">文字字体颜色</string><stringname="text_pref_text_color_summ">

文字字体颜色,请输入一个数值,格式:#FFFFFFFF</string>

</resources>为了显示动画,还需要在res目录下新建一个anim的子目录,并在其目录下新建一个名为my_scale.xml的动画文件,修改该文件后的内容如下:<?xmlversion="1.0"encoding="utf-8"?><scalexmlns:android="/apk/res/android"android:interpolator="@android:anim/accelerate_interpolator"android:fromXScale="0"android:toXScale="1"android:fromYScale="0"android:toYScale="1"android:duration="4000"android:pivotX="50%"android:pivotY="50%"android:fillAfter="true"></scale>现在构建首选项Activity,新建名为MySettingsActivity的Java类文件,修改该文件为如下内容:packagecom.example.ch1102;

importandroid.os.Bundle;importandroid.preference.PreferenceActivity;

@SuppressWarnings("deprecation")publicclassMySettingsActivityextendsPreferenceActivity{publicstaticStringPREF_ANIMATION="pref_animation";publicstaticStringPREF_LANG_TYPE="pref_lang_type";publicstaticStringPREF_TEXT_SIZE="pref_text_size";publicstaticStringPREF_TEXT_COLOR="pref_text_color";

@SuppressWarnings("deprecation")@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);addPreferencesFromResource(R.xml.my_settings);}}现在回到MainActivity类,看一下如何获得和使用在首选项Activity中所设置的首选项值。修改MainActivity.java文件为如下内容:packagecom.example.ch1102;

importandroid.content.Intent;importandroid.content.SharedPreferences;importandroid.graphics.Color;importandroid.os.Bundle;importandroid.preference.PreferenceManager;importandroid.view.View;importandroid.view.animation.Animation;importandroid.view.animation.AnimationUtils;importandroid.widget.Button;importandroid.widget.TextView;

importandroidx.activity.EdgeToEdge;importandroidx.annotation.Nullable;importandroidx.appcompat.app.AppCompatActivity;importandroidx.core.graphics.Insets;importandroidx.core.view.ViewCompat;importandroidx.core.view.WindowInsetsCompat;

publicclassMainActivityextendsAppCompatActivityimplementsSharedPreferences.OnSharedPreferenceChangeListener,View.OnClickListener{privateTextViewtv;

@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_main);ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main),(v,insets)->{InsetssystemBars=insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left,systemBars.top,systemBars.right,systemBars.bottom);returninsets;});Buttonbtn=findViewById(R.id.id_btn);btn.setOnClickListener(this);

tv=findViewById(R.id.id_textview);

SharedPreferencessettings=PreferenceManager.getDefaultSharedPreferences(this);settings.registerOnSharedPreferenceChangeListener(this);

Stringlang_type=settings.getString(MySettingsActivity.PREF_LANG_TYPE,"1");if(lang_type.equalsIgnoreCase("1"))tv.setText(R.string.text_hello_world_en);elsetv.setText(R.string.text_hello_world_cn);

Stringtext_size=settings.getString(MySettingsActivity.PREF_TEXT_SIZE,"16");tv.setTextSize(Float.parseFloat(text_size));

Stringtext_color=settings.getString(MySettingsActivity.PREF_TEXT_COLOR,"#FF000000");tv.setTextColor(Color.parseColor(text_color));

booleananimation=settings.getBoolean(MySettingsActivity.PREF_ANIMATION,false);if(animation){Animationscale=AnimationUtils.loadAnimation(this,R.anim.my_scale);tv.startAnimation(scale);}}@OverridepublicvoidonSharedPreferenceChanged(SharedPreferencessettings,@NullableStringkey){assertkey!=null;if(key.equalsIgnoreCase(MySettingsActivity.PREF_ANIMATION)){booleananimation=settings.getBoolean(MySettingsActivity.PREF_ANIMATION,false);if(animation){Animationscale=AnimationUtils.loadAnimation(this,R.anim.my_scale);tv.startAnimation(scale);}}elseif(key.equalsIgnoreCase(MySettingsActivity.PREF_LANG_TYPE)){Stringlang_type=settings.getString(MySettingsActivity.PREF_LANG_TYPE,"1");if(lang_type.equalsIgnoreCase("1"))tv.setText(R.string.text_hello_world_en);elsetv.setText(R.string.text_hello_world_cn);}elseif(key.equalsIgnoreCase(MySettingsActivity.PREF_TEXT_COLOR)){Stringtext_color=settings.getString(MySettingsActivity.PREF_TEXT_COLOR,"#FFFFFFFF");tv.setTextColor(Color.parseColor(text_color));}elseif(key.equalsIgnoreCase(MySettingsActivity.PREF_TEXT_SIZE)){Stringtext_size=settings.getString(MySettingsActivity.PREF_TEXT_SIZE,"16");tv.setTextSize(Float.parseFloat(text_size));}}

@OverridepublicvoidonClick(Viewv){Intenti=newIntent(this,MySettingsActivity.class);this.startActivity(i);}}需要在AndroidManifest.xml中配置MySettingActivity,如下:<?xmlversion="1.0"encoding="utf-8"?><manifestxmlns:android="/apk/res/android"xmlns:tools="/tools">

<applicationandroid:allowBackup="true"android:dataExtractionRules="@xml/data_extraction_rules"android:fullBackupContent="@xml/backup_rules"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/Theme.Ch1102"><activityandroid:name=".MainActivity"android:exported="true"><intent-filter><actionandroid:name="ent.action.MAIN"/><categoryandroid:name="ent.category.LAUNCHER"/></intent-filter></activity>

<activityandroid:name=".MySettingsActivity"android:exported="false"/>

</application>

</manifest>11.4在应用程序沙箱/家目录下存储数据如前所述,任何一个Android应用程序,在被安装到Android系统中时,系统都将在/data/data目录下,以这个应用程序的包名为名称为这个应用程序创建一个子目录。有时成这个目录为沙箱目录,或者家目录,或者私有目录。程序可以在这个子目录下创建只有自己才可以访问的子目录或文件。本节将介绍如何在应用程序的私有目录下创建和使用文件。Activity提供了如下的用于操作应用程序私有目录的方法(这些方法是在Context类中定义的,因为Activity是Context的子类,自然也继承了这些方法)。(1)FileActivity.getFilesDir()返回应用程序私有目录全路径的File对象。例如,如果应用程序的包名为com.ttt.mysample,则这个File对象的全路径为/data/data/com.ttt.mysample/files。(2)FilegetDir(Stringname,intmode)在应用程序的私有目录下创建或返回一个名字为“app_”+name参数的子目录File对象,设置mode参数为0即可。(3)booleandeleteFile(Stringname)在应用程序的私有目录下删除一个名称为name的文件。(4)String[]fileList()返回应用程序私有目录下的所有子目录或文件名。(5)FileOutputStreamopenFileOutput(Stringname,intmode)在应用程序的私有目录下,打开或新建一个名称为name的文件用于写入数据,设置mode参数为0即可。(6)FileInputStreamopenFileInput(Stringname)在应用程序的私有目录下,打开名称为name的文件用于从中读取数据。除了上面这些方法,还可以使用java.io中提供的类及方法对应用程序私有目录下的任何文件或目录进行操作。下面举一个例子说明如何操作家目录下的文件。这个例子只是简单的在家目录下新建的名称为resume.text文件中写入几个文字。为此,新建名称为ch1103的工程,修改主界面布局activity_main.xml为如下代码:<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="/apk/res/android"xmlns:tools="/tools"android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity">

<Buttonandroid:id="@+id/btn01"android:layout_width="match_parent"android:layout_height="64dp"android:text="保存数据到文件"android:layout_margin="5dp"android:textSize="20sp"/>

<Buttonandroid:id="@+id/btn02"android:layout_width="match_parent"android:layout_height="64dp"android:text="读取并显示"android:layout_margin="5dp"android:textSize="20sp"/>

<TextViewandroid:id="@+id/tv01"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:textSize="20sp"android:layout_margin="5dp"/>

</LinearLayout>修改MainActivity.java为如下代码:packagecom.example.ch1103;

importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;importandroid.widget.TextView;

importandroidx.activity.EdgeToEdge;importandroidx.appcompat.app.AppCompatActivity;importandroidx.core.graphics.Insets;importandroidx.core.view.ViewCompat;importandroidx.core.view.WindowInsetsCompat;

importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.UnsupportedEncodingException;importjava.nio.charset.StandardCharsets;

publicclassMainActivityextendsAppCompatActivityimplementsView.OnClickListener{TextViewtv01;

@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_main);ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main),(v,insets)->{InsetssystemBars=insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left,systemBars.top,systemBars.right,systemBars.bottom);returninsets;});

Buttonbtn01=findViewById(R.id.btn01);btn01.setOnClickListener(this);Buttonbtn02=findViewById(R.id.btn02);btn02.setOnClickListener(this);

tv01=findViewById(R.id.tv01);}

@OverridepublicvoidonClick(Viewv){intid=v.getId();if(id==R.id.btn01){try{FileOutputStreamfos=this.openFileOutput("resume.text",0);fos.write("你好,这是一段描述文字!".getBytes(StandardCharsets.UTF_8));fos.close();}catch(IOExceptione){thrownewRuntimeException(e);}}elseif(id==R.id.btn02){try{FileInputStreamfis=this.openFileInput("resume.text");byte[]b=newbyte[fis.available()];intlen=fis.read(b);tv01.setText(newString(b,StandardCharsets.UTF_8));fis.close();}catch(IOExceptione){thrownewRuntimeException(e);}}}}11.5使用SQLite数据库保存数据当程序需要存储的数据量比较大,并且需要对数据进行复杂的操作时,数据库则是最佳的选项技术。针对Android平台,SQLite则是最佳选择。11.5.1SQLite数据库简介SQLite是开源的、免费的数据库管理系统。与一般的基于C/S模式的数据库管理系统不同,例如MicrosoftSQLServer、MySQL,数据库数据存储在称为服务器的计算机系统上,并通过数据库管理系统的服务器端程序来管理。需要使用数据库数据的程序,称为客户端程序。它通过某种通信协议,例如TCP/IP与数据库管理系统的服务器端程序通信来进行数据库数据的操作。SQLite则全然不同,它不是基于C/S模式的,它只是一个C语言库,需要使用SQLite数据库的程序只需要调用这个程序包中的函数即可创建数据库、访问数据库中的数据等。Android整合了SQLite数据库管理系统,将SQLite的C语言程序包进行了Java封装,提供了基于Java语言的类库。因此,在Android程序开发中,可以使用SQLite提供的Java接口来创建及访问SQLite数据库。可以使用SQL规范中定义的SQL语言来创建和操作SQLite数据库。需要注意的是,对于所支持的数据类型,其他的基于C/S模式的数据库管理系统都提供了十分丰富的数据类型,例如int、char、varchar、text、image、real等。SQLite也支持这些数据类型,但是,SQLite则采用自己的一套称为“TypeAffinity”的机制进行数据类型自动映射,也就是将所有的数据类型都映射到如下的5种类型之一中。(1)TEXT。字符串类型;(2)NUMBERIC。精确表示的数值类型;(3)INTEGER。整数类型;(4)REAL类型。采用8字节表示的IEEE浮点数据类型;(5)BLOB类型。二进制数据类型。Android应用开发者不需要对这套“TypeAffinity”机制进行详细了解,在创建数据库表时,使用如上的5种数据类型就够了。11.5.2在Android中使用SQLite数据库Android提供了完整的操作SQLite数据库的Java类库,其中一个非常重要和常用的类就是SQLiteOpenHelper类。在需要创建和使用SQLite数据库时,应该继承这个类,并重写其中的onCreate()方法来创建自己的数据表。下面举一个例子说明如何使用SQLiteOpenHelper类来创建SQLite数据库,以及在数据库中创建数据表。这个例子要创建的数据库名称为“Teach.db”,其中包含3张表:student表、course表和score表,其中分别存放学生的基本信息、课程的基本信息和学生成绩的基本信息。这3张表的结构定义如表所示。student表结构定义。course表结构定义。score表结构定义。字段名称数据类型备

注_idINTEGER自增、主键student_nameTEXT学生姓名student_birthTEXT学生出生日期student_phoneTEXT联系电话student_photoBLOB学生头像字段名称数据类型备

注_idINTEGER自增、主键course_nameTEXT课程名称course_memoTEXT课程介绍字段名称数据类型备

注_idINTEGER自增、主键student_idINTEGER外键参照student表的student_id字段course_idINTEGER外键参照course表的course_id字段score_scoreREAL学生课程成绩创建一个Android程序来创建需要的数据库和在数据库中创建需要的表。为此,新建名为ch1104的工程,并新建一个名为com.example.ch1104.database的包,在这个包下新建名为MyDataBaseHelper的Java类文件。修改MyDataBaseHelper.java文件,内容如下:packagecom.example.ch1104.database;

importandroid.content.Context;importandroid.database.sqlite.SQLiteDatabase;importandroid.database.sqlite.SQLiteOpenHelper;

publicclassMyDataBaseHelperextendsSQLiteOpenHelper{

privatestaticfinalStringDATABASE_NAME="Teach.db";privatestaticfinalintDATABASE_VERSION=1;

privatestaticfinalStringcreate_student="CREATETABLEstudent("+"_idINTEGERPRIMARYKEY,"+"student_nameTEXT,"+"student_birthTEXT,"+"student_phoneTEXT,"+"student_photoBLOB"+");";privatestaticfinalStringcreate_course="CREATETABLEcourse("+"_idINTEGERPRIMARYKEY,"+"course_nameTEXT,"+"course_memoTEXT"+");";privatestaticfinalStringcreate_score="CREATETABLEscore("+"_idINTEGERPRIMARYKEY,"+"student_idINTEGER,"+"course_idINTEGER,"+"FOREIGNKEY(student_id)REFERENCESstudent(student_id),"+"FOREIGNKEY(course_id)REFERENCEScourse(course_id)"+");";

publicMyDataBaseHelper(Contextcontext){super(context,DATABASE_NAME,null,DATABASE_VERSION);}

@OverridepublicvoidonCreate(SQLiteDatabasedb){db.execSQL(create_student);db.execSQL(create_course);db.execSQL(create_score);}

@OverridepublicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){db.execSQL("droptablescore");db.execSQL("droptablestudent");db.execSQL("droptablecourse");

onCreate(db);}}现在继续完善这个程序。例子程序的功能是可以在student表中插入数据,然后通过一个ListView将student表中的数据显示出来。现在修改res/layout/activity_main.xml主界面布局文件,修改后的内容如下:<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="/apk/res/android"xmlns:app="/apk/res-auto"xmlns:tools="/tools"android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity">

<Buttonandroid:id="@+id/id_button"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="@string/text_button"/>

<ListViewandroid:id="@+id/id_listview"android:layout_width="match_parent"android:layout_height="wrap_content"/>

</LinearLayout>在res/layout工程目录下新建一个列表项布局文件list_item.xml,文件内容如下:<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="/apk/res/android"android:orientation="horizontal"android:layout_width="match_parent"android:layout_height="match_parent">

<ImageViewandroid:id="@+id/id_li_photo"android:layout_width="64dp"android:layout_height="64dp"android:scaleType="fitCenter"android:contentDescription="@string/hello_world"/>

<Viewandroid:layout_width="10dp"android:layout_height="64dp"/><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical">

<TextViewandroid:id="@+id/id_li_id"android:layout_width="match_parent"android:layout_height="wrap_content“/>

<TextViewandroid:id="@+id/id_li_name"android:layout_width="match_parent"android:layout_height="wrap_content“/>

<TextViewandroid:id="@+id/id_li_birth"android:layout_width="match_parent"android:layout_height="wrap_content“/>

<TextViewandroid:id="@+id/id_li_phone"android:layout_width="match_parent"android:layout_height="wrap_content“/>

</LinearLayout></LinearLayout>修改res/values/strings.xml文件,在其中定义按钮文字的字符串引用,修改后的内容如下:<resources><stringname="app_name">ch1104</string>

<stringname="text_button">插入并显示学生记录</string><stringname="hello_world">Helloworld!</string>

</resources>新建名为MySimpleCursorAdapter的Java类,修改其中的内容为如下代码:packagecom.example.ch1104.adapters;

importandroid.content.Context;importandroid.database.Cursor;importandroid.graphics.Bitmap;importandroid.graphics.BitmapFactory;importandroid.view.LayoutInflater;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.ImageView;importandroid.widget.SimpleCursorAdapter;importandroid.widget.TextView;

publicclassMySimpleCursorAdapterextendsSimpleCursorAdapter{privatefinalintlayout;privatefinalCursorc;privatefinalString[]from;privatefinalint[]to;

privatefinalLayoutInflatermInflater;

@SuppressWarnings("deprecation")publicMySimpleCursorAdapter(Contextcontext,intlayout,Cursorc,String[]from,int[]to){super(context,layout,c,from,to);

this.layout=layout;this.c=c;this.from=from;this.to=to;

mInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);}@O

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论