我正在尝试在 sdcard 上生成 XML 文件。我已经在 Manifest 文件中添加了用户权限,但是当我通过 USB 插入手机并在 eclipse 中运行应用程序时,第一次创建了 xml 文件,但是当我再次通过手机或通过 eclipse 运行应用程序时,它不会得到创建的。为了创建文件,我必须通过 USB 重新连接我的手机,并且它也只创建一次。请帮我。
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(); }});
}
}