Java 在Android中传递变量
我的Android应用程序中当前有此页面: 我想将添加到这些字段中的数据传递到设备上存储的.txt文件中 代码如下:Java 在Android中传递变量,java,android,eclipse,variables,Java,Android,Eclipse,Variables,我的Android应用程序中当前有此页面: 我想将添加到这些字段中的数据传递到设备上存储的.txt文件中 代码如下: <Button android:id="@+id/Button02" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/btn2" /> <ScrollView android:layout_width="match_p
<Button
android:id="@+id/Button02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/btn2" />
<ScrollView android:layout_width="match_parent" android:id="@+id/scrollView1" android:layout_height="wrap_content">
<LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal">
<TextView android:text="Please insert details below to confirm you have completed and understood the app" android:id="@+id/textView1" android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_gravity="center_horizontal">
</TextView>
</LinearLayout>
</ScrollView>
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="Forename" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="Surname" />
<EditText
android:id="@+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
android:text="Staff ID" />
<Button
android:id="@+id/buttonformdata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
现在我确定变量是在有编辑文本字段的地方传递的?我如何链接变量以使其工作?如果需要我的项目的代码,我可以上传它,如果这样做会更容易。我假设您希望在用户单击“提交”按钮时将数据写入文件。您可以在附加到此按钮的侦听器的
onClick()
方法中执行此操作,如下所示:
try{
FileOutputStream fout = openFileOutput(“yourfile.txt”,MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(editText1.getText().toString()+" ");
osw.write(editText2.getText().toString()+" ");
osw.write(editText3.getText().toString()+" ");
osw.close();
fout.close();
}catch(Exception e){
//do the exception handling
}
如果您打算使用自己的类来处理所有写入和读取操作,则可以在onClick()
方法中创建该类的实例,并使用适当的参数对其调用读取/写入方法
try{
FileOutputStream fout = openFileOutput(“yourfile.txt”,MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(editText1.getText().toString()+" ");
osw.write(editText2.getText().toString()+" ");
osw.write(editText3.getText().toString()+" ");
osw.close();
fout.close();
}catch(Exception e){
//do the exception handling
}