我試圖在SD卡上生成XML文件。我已經在Manifest文件中添加了用戶權限,但是當我通過usb插入手機並在eclipse中運行應用程序時,第一次創建了xml文件,但是當我再次通過手機或通過eclipse運行應用程序時,它不能獲取創建。爲了創建文件,我必須通過USB重新連接手機,並且只能創建一次。請幫幫我。XML文件只創建一次而不是每次執行應用程序時
public class MainActivity extends Activity {
TextView myTextView;
EditText E1;
EditText E2;
EditText E3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1= (Button) findViewById(R.id.button1);
Button b3= (Button) findViewById(R.id.button3);
E1 = (EditText) findViewById(R.id.editText1);
E2 = (EditText) findViewById(R.id.editText2);
E3 = (EditText) findViewById(R.id.editText3);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
try {
docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Class");
doc.appendChild(rootElement);
Element student = doc.createElement("Student");
rootElement.appendChild(student);
Element firstname = doc.createElement("firstname"); firstname.appendChild(doc.createTextNode(E1.getText().toString()));
student.appendChild(firstname);
Element Email = doc.createElement("Email");
Email.appendChild(doc.createTextNode(E2.getText().toString()));
student.appendChild(Email);
Element Roll = do c.createElement("Roll_No");
Roll.appendChild(doc.createTextNode(E3.getText().toString()));
student.appendChild(Roll);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
File FF=new File(Environment.getExternalStorageDirectory()+"//new.xml");
try {
FF.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
StreamResult result = new StreamResult(FF);
transformer.transform(source, result);
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (TransformerException e) {
e.printStackTrace();}
Toast.makeText(getApplicationContext(), Environment.getExternalStorageDirectory().toString(), Toast.LENGTH_LONG).show(); }
});
b3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Close the application
finish(); }});
}
}
我試圖通過你提供的代碼,現在該文件是不是所有得到建立。 – user2044296 2013-05-11 10:13:41
是否引發異常?請提供logcat。 – tbkn23 2013-05-11 10:59:50