一、把数据存储到文件并取数据显示在界面上
在Android应用程序中的存储数据的方式
1、文件
2、使用SharedPreferences保存数据
3、使用SQLite数据库
4、使用ContentProvider内容提供者
5、通过网络把数据存储到服务器上
1、保存数据到文件上
代码:
a、布局文件
/********************************************************************** * * A cube 'state' is a vector with 40 entries, the first 20 * are a permutation of {0,...,19} and describe which cubie is at * a certain position (regarding the input ordering). The first * twelve are for edges, the last eight for corners. * * The last 20 entries are for the orientations, each describing * how often the cubie at a certain position has been turned * counterclockwise away from the correct orientation. Again the * first twelve are edges, the last eight are corners. The values * are 0 or 1 for edges and 0, 1 or 2 for corners. * **********************************************************************/ #include #include #include #include
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/et_username" android:hint="请输入用户名" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/et_pwd" android:inputType="textPassword" android:hint="请输入密码" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="保存" android:onClick="save" /> /**************************************************/ b、源代码 MainActivity.java public class MainActivity extends Activity { private EditText et_username;//做声明 private EditText et_pwd; protected void onCreate(Bundle savedInstanceState) { //调用父类的构造方法 super.onCreate(savedInstanceState); //设置当前Activity显示内容为main.xml布局 setContentView(R.layout.activity_main); et_username=(EditText)findViewById(R.id.et_username); et_pwd=(EditText)findViewById(R.id.et_pwd); try{ //从文件中读取数据 File file=new File("/data/data/package01/files/info.text"); FileReader fr=new FileReader(file); BufferedReader br=new BufferedReader(fr); String info=br.readLine(); //把数据显示在输入框中 if(!TextUtils.isEmpty(info)) { String[] array=info.split("##"); String username=array[0]; String pwd=array[1]; et_username.setText(username); et_pwd.setText(pwd); } }catch(Exception e){ e.printStackTrace(); } } } public void save(View view){ String username=et_username.getText().toString().trim(); String pwd=et_pwd.getText().toString().trim(); if(TextUtils.isEmpty(username) || TextUtils.isEmpty(pwd)){ Tost.makeText(this,"用户名或者密码不存在",Toast.LENGTH_SHORT).show(); return; }else{ //把用户名和密码保存到文件中 FileOutputStream fos=this.openFileOutput("info.text",Context.MODE_PRIVATE); fos.write((username+"##"+pwd).getBytes()); fos.close; }catch(Exception e){ e.printStackTrace(); } }