将列表视图中的项目保存到 android 中的文本文件
Save an item from a listview in to a textfile in android
我正在浏览来自外部 USB 存储(使用 otg 电缆,连接在 tablet/android phone)中的 xml 文件以进行解析。
步骤:
- 从外部 USB 存储浏览文件
- 解析 xml 文件
- 将文件保存为文本文件
目前,我现在能够浏览和解析 xml 文件,然后显示已解析的文件,其中它在列表视图中显示所需的信息。现在,我想将显示的信息保存为文本文件,保存到平板的外置sd卡中。这是代码:
Model.java :
public class Model {
String _model;
String _part;
String _sw;
String _desc;
// constructor
public Model() {
}
// constructor with parameters
public Model(String model, String part, String sw, String desc) {
this._model = model;
this._part = part;
this._sw = sw;
this._desc = desc;
}
// Set all methods
public void setModel(String model) {
this._model = model;
}
public void setPart(String part) {
this._part = part;
}
public void setSw(String sw) {
this._sw = sw;
}
public void setDesc(String desc) {
this._desc = desc;
}
// Get all methods
public String getModel() {
return this._model;
}
public String getPart() {
return this._part;
}
public String getSw() {
return this._sw;
}
public String getDesc() {
return this._desc;
}
//
@Override
public String toString() {
return "\n" + "Device" + "\n" + "\n"
+ "Model ID : " + _model + "\n"
+ "Part Number : " + _part + "\n"
+ "Software Version: " + _sw + "\n"
+ "Description : " + _desc ;
}
}
ModelParser.java :
public class ModelParser extends DefaultHandler{
static final String ERROR = "Errors";
static final String ID = "ID";
static final String PART = "PartNumber";
static final String SW = "SoftwareVersion";
static final String DESC = "Description";
private boolean done = false;
private String currentTag = null;
private Model current = null;
private ArrayList<Model> model = new ArrayList<Model>();
public ArrayList<Model> getItemsList() {
return model;
}
public ArrayList<Model> parse(Context context) {
try {
String file = ReadSystemActivity.getFilename();
file.toString();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
FileInputStream fis = new FileInputStream(file);
parser.setInput(new InputStreamReader(fis));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT && !done) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
model = new ArrayList<Model>();
break;
case XmlPullParser.START_TAG:
currentTag = parser.getName();
if (currentTag.equalsIgnoreCase(ERROR)) {
current = new Model();
}
else if (current != null) {
if (currentTag.equalsIgnoreCase(ID)) {
current.setModel(parser.nextText());
} else if (currentTag.equalsIgnoreCase(PART)) {
current.setPart(parser.nextText());
} else if (currentTag.equalsIgnoreCase(SW)) {
current.setSw(parser.nextText());
}else if (currentTag.equalsIgnoreCase(DESC)) {
current.setDesc(parser.nextText());
}
}
break;
case XmlPullParser.END_TAG:
currentTag = parser.getName();
if (currentTag.equalsIgnoreCase(ERROR) && current != null) {
model.add(current);
} else if (currentTag.equalsIgnoreCase(ERROR)) {
done = true;
}
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return model;
}
}
和ReadActivity.java:
public class ReadActivity extends ListActivity implements OnClickListener {
public List<Model> model = null;
private String filename = "SystemInfo.txt";
String modd = modId.getModel();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
new LoadSystemTask().execute();
Button save = (Button) findViewById(R.id.btnSave);
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
if (isSDCardWritable()) {
StringBuilder locationStrBuilder = new StringBuilder();
locationStrBuilder.append("Model ID: "+ modd);
String locationStr = locationStrBuilder.toString();
try {
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+"/FileReader");
directory.mkdirs();
File myFile = new File(directory, filename);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(locationStr);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing to SD Card",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
} }
else
{
// SD Card Not Available
Toast.makeText(getBaseContext(),"SD Card Not Available",Toast.LENGTH_SHORT).show();
} //else
}// onClick
}); // btnSave
}
private class LoadSystemTask extends AsyncTask<String, Void, List<Model>> {
@Override
protected List<Model> doInBackground(String... args) {
// CALL XMLPULLPARSER & RETURN A LIST
ModelParser parser = new ModelParser();
model = parser.parse(getBaseContext());
return model;
}
@Override
protected void onPostExecute(List<Model> models) {
ArrayAdapter<Model> adapter = new ArrayAdapter<Model>(getBaseContext(), android.R.layout.simple_list_item_1, models);
setListAdapter(adapter);
}
}
public boolean isSDCardWritable() {
String status = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(status))
{
return true;
}
return false;
} //isSDCardWritable
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
问题是,我想保存 ID,但是当我单击保存按钮时,我在 SystemInfo.txt 中得到一个空值。
您正在将模型存储在另一个对象中并尝试从新对象中检索它。
这是您在 ModelParser
中存储模型对象的地方
current = new GarminModel()
而您正试图从 ReadActivity
中的新对象中检索它
GarminModel modId = new GarminModel();
String modd = modId.getModel();
通过在 ReadActivity
中调用 ModelParser's
getItemsList()
获取对模型数组列表的引用,并尝试从中获取模型对象
检查下面代码中下面两行的位置
ModelParser parser = new ModelParser();
ArrayList<Model> modelList = parser.getItemsList();
Model modd = modelList.get(0);
注意需要去掉ModelParser parser = new ModelParser();来自 LoadSystemTask
public class ReadActivity extends ListActivity implements OnClickListener {
public List<Model> model = null;
private String filename = "SystemInfo.txt";
ModelParser parser = new ModelParser();
//-----------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
new LoadSystemTask().execute();
Button save = (Button) findViewById(R.id.btnSave);
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
if (isSDCardWritable()) {
ArrayList<Model> modelList = parser.getItemsList();
//-----
Model modd = modelList.get(0);
StringBuilder locationStrBuilder = new StringBuilder();
locationStrBuilder.append("Model ID: "+ modd);
String locationStr = locationStrBuilder.toString();
try {
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+"/FileReader");
directory.mkdirs();
File myFile = new File(directory, filename);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(locationStr);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing to SD Card",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
} }
else
{
// SD Card Not Available
Toast.makeText(getBaseContext(),"SD Card Not Available",Toast.LENGTH_SHORT).show();
} //else
}// onClick
}); // btnSave
}
private class LoadSystemTask extends AsyncTask<String, Void, List<Model>> {
@Override
protected List<Model> doInBackground(String... args) {
// CALL XMLPULLPARSER & RETURN A LIST
model = parser.parse(getBaseContext());
return model;
}
我正在浏览来自外部 USB 存储(使用 otg 电缆,连接在 tablet/android phone)中的 xml 文件以进行解析。
步骤:
- 从外部 USB 存储浏览文件
- 解析 xml 文件
- 将文件保存为文本文件
目前,我现在能够浏览和解析 xml 文件,然后显示已解析的文件,其中它在列表视图中显示所需的信息。现在,我想将显示的信息保存为文本文件,保存到平板的外置sd卡中。这是代码:
Model.java :
public class Model {
String _model;
String _part;
String _sw;
String _desc;
// constructor
public Model() {
}
// constructor with parameters
public Model(String model, String part, String sw, String desc) {
this._model = model;
this._part = part;
this._sw = sw;
this._desc = desc;
}
// Set all methods
public void setModel(String model) {
this._model = model;
}
public void setPart(String part) {
this._part = part;
}
public void setSw(String sw) {
this._sw = sw;
}
public void setDesc(String desc) {
this._desc = desc;
}
// Get all methods
public String getModel() {
return this._model;
}
public String getPart() {
return this._part;
}
public String getSw() {
return this._sw;
}
public String getDesc() {
return this._desc;
}
//
@Override
public String toString() {
return "\n" + "Device" + "\n" + "\n"
+ "Model ID : " + _model + "\n"
+ "Part Number : " + _part + "\n"
+ "Software Version: " + _sw + "\n"
+ "Description : " + _desc ;
}
}
ModelParser.java :
public class ModelParser extends DefaultHandler{
static final String ERROR = "Errors";
static final String ID = "ID";
static final String PART = "PartNumber";
static final String SW = "SoftwareVersion";
static final String DESC = "Description";
private boolean done = false;
private String currentTag = null;
private Model current = null;
private ArrayList<Model> model = new ArrayList<Model>();
public ArrayList<Model> getItemsList() {
return model;
}
public ArrayList<Model> parse(Context context) {
try {
String file = ReadSystemActivity.getFilename();
file.toString();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
FileInputStream fis = new FileInputStream(file);
parser.setInput(new InputStreamReader(fis));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT && !done) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
model = new ArrayList<Model>();
break;
case XmlPullParser.START_TAG:
currentTag = parser.getName();
if (currentTag.equalsIgnoreCase(ERROR)) {
current = new Model();
}
else if (current != null) {
if (currentTag.equalsIgnoreCase(ID)) {
current.setModel(parser.nextText());
} else if (currentTag.equalsIgnoreCase(PART)) {
current.setPart(parser.nextText());
} else if (currentTag.equalsIgnoreCase(SW)) {
current.setSw(parser.nextText());
}else if (currentTag.equalsIgnoreCase(DESC)) {
current.setDesc(parser.nextText());
}
}
break;
case XmlPullParser.END_TAG:
currentTag = parser.getName();
if (currentTag.equalsIgnoreCase(ERROR) && current != null) {
model.add(current);
} else if (currentTag.equalsIgnoreCase(ERROR)) {
done = true;
}
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return model;
}
}
和ReadActivity.java:
public class ReadActivity extends ListActivity implements OnClickListener {
public List<Model> model = null;
private String filename = "SystemInfo.txt";
String modd = modId.getModel();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
new LoadSystemTask().execute();
Button save = (Button) findViewById(R.id.btnSave);
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
if (isSDCardWritable()) {
StringBuilder locationStrBuilder = new StringBuilder();
locationStrBuilder.append("Model ID: "+ modd);
String locationStr = locationStrBuilder.toString();
try {
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+"/FileReader");
directory.mkdirs();
File myFile = new File(directory, filename);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(locationStr);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing to SD Card",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
} }
else
{
// SD Card Not Available
Toast.makeText(getBaseContext(),"SD Card Not Available",Toast.LENGTH_SHORT).show();
} //else
}// onClick
}); // btnSave
}
private class LoadSystemTask extends AsyncTask<String, Void, List<Model>> {
@Override
protected List<Model> doInBackground(String... args) {
// CALL XMLPULLPARSER & RETURN A LIST
ModelParser parser = new ModelParser();
model = parser.parse(getBaseContext());
return model;
}
@Override
protected void onPostExecute(List<Model> models) {
ArrayAdapter<Model> adapter = new ArrayAdapter<Model>(getBaseContext(), android.R.layout.simple_list_item_1, models);
setListAdapter(adapter);
}
}
public boolean isSDCardWritable() {
String status = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(status))
{
return true;
}
return false;
} //isSDCardWritable
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
问题是,我想保存 ID,但是当我单击保存按钮时,我在 SystemInfo.txt 中得到一个空值。
您正在将模型存储在另一个对象中并尝试从新对象中检索它。
这是您在 ModelParser
current = new GarminModel()
而您正试图从 ReadActivity
GarminModel modId = new GarminModel();
String modd = modId.getModel();
通过在 ReadActivity
中调用 ModelParser's
getItemsList()
获取对模型数组列表的引用,并尝试从中获取模型对象
检查下面代码中下面两行的位置
ModelParser parser = new ModelParser();
ArrayList<Model> modelList = parser.getItemsList();
Model modd = modelList.get(0);
注意需要去掉ModelParser parser = new ModelParser();来自 LoadSystemTask
public class ReadActivity extends ListActivity implements OnClickListener {
public List<Model> model = null;
private String filename = "SystemInfo.txt";
ModelParser parser = new ModelParser();
//-----------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
new LoadSystemTask().execute();
Button save = (Button) findViewById(R.id.btnSave);
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
if (isSDCardWritable()) {
ArrayList<Model> modelList = parser.getItemsList();
//-----
Model modd = modelList.get(0);
StringBuilder locationStrBuilder = new StringBuilder();
locationStrBuilder.append("Model ID: "+ modd);
String locationStr = locationStrBuilder.toString();
try {
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+"/FileReader");
directory.mkdirs();
File myFile = new File(directory, filename);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(locationStr);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing to SD Card",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
} }
else
{
// SD Card Not Available
Toast.makeText(getBaseContext(),"SD Card Not Available",Toast.LENGTH_SHORT).show();
} //else
}// onClick
}); // btnSave
}
private class LoadSystemTask extends AsyncTask<String, Void, List<Model>> {
@Override
protected List<Model> doInBackground(String... args) {
// CALL XMLPULLPARSER & RETURN A LIST
model = parser.parse(getBaseContext());
return model;
}