How do I write to a .txt file in Android? - android

I have an app that needs to read and write to a text file. I have it reading, but I don't have it writing. The idea is that when I click the save button on the screen, its going to save all the info that has been put into the textviews into an array and the write each segment of the array into the text file. This is my code for the writing portion:
public class AddOrModify extends Activity {
private Button Savebtn;
private Button Cancelbtn;
private EditText NameofRoute;
private EditText Address1;
private EditText City1;
private EditText State1;
private EditText Zip1;
private EditText Address2;
private EditText City2;
private EditText State2;
private EditText zip2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_or_modify);
Savebtn = (Button)findViewById(R.id.savebtn);
Savebtn.setOnClickListener(new btnlistenersave());
Cancelbtn = (Button)findViewById(R.id.cancelbtn);
Cancelbtn.setOnClickListener(new btnlistenercancel());
}
private class btnlistenersave implements View.OnClickListener{
public void onClick(View v) {
NameofRoute = (EditText)findViewById(R.id.NameofRoute);
Address1 = (EditText)findViewById(R.id.editAddress1);
City1 = (EditText)findViewById(R.id.City1);
State1= (EditText)findViewById(R.id.State1);
Zip1 = (EditText)findViewById(R.id.Zip1);
Address2= (EditText)findViewById(R.id.Address2);
City2 = (EditText)findViewById(R.id.City2);
State2 = (EditText)findViewById(R.id.State2);
zip2 = (EditText)findViewById(R.id.Zip2);
//String[] mySettings ={NameofRouteinput,Address1input,City1input, State1input,Zip1input,Address2input,City2input,State2input,Zip2input,";"};
// if(mySettings != null){
try{
String NameofRouteinput = NameofRoute.getText().toString();
String Address1input = Address1.getText().toString();
String City1input = City1.getText().toString();
String State1input=State1.getText().toString();
String Zip1input = Zip1.getText().toString();
String Address2input =Address2.getText().toString();
String City2input = City2.getText().toString();
String State2input = State2.getText().toString();
String Zip2input= zip2.getText().toString();
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("myaddress.txt",0));
String[] mySettings ={NameofRouteinput,Address1input,City1input, State1input,Zip1input,Address2input,City2input,State2input,Zip2input,";"};
for(int i =0; i < mySettings.length; i++)
out.write(mySettings[i]);
out.close();
}
catch (java.io.IOException e){
}
Intent i = new Intent(AddOrModify.this, Frontpage.class);
startActivity(i);
}
}
private class btnlistenercancel implements View.OnClickListener{
public void onClick(View v) {
Intent i = new Intent(AddOrModify.this, Frontpage.class);
startActivity(i);
}
}
}

with mari's solution i was getting
java.lang.IllegalArgumentException: contains a path separator
then i tried following and it worked for me
File root = new File(DIRECTORY_PATH);
File gpxfile = new File(root, "samples.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append("First string is here to be written.");
writer.flush();
writer.close();
you can loop it to write multiple lines

You can use FileOutputStream instead of OutputStreamWriter, something like this:
File file = getFileStreamPath("test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE);
for (String string: data){
writer.write(string.getBytes());
writer.flush();
}
writer.close();
Check the android docs.

Related

Generate PDF file and attach to e-mail

first post here.
I have read all similar posts without finding any answer, i'm a newbie at dev in general.
Here is what i'm looking for:
On button click, the code generates a PDF with some info, and i just want to send the created pdf by mail.
First problem is when i choose an email app to send the mail, i got a message "Impossible to attach file".
Second problem is that the created file is not readable on the phone while it's readable on PC.
By searching i found out that it may be in relation with permission. I tried setReadablemethod without result. Android studio makes a hint (result of setReadable is ignored).
Code :
public class VerifList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verif_list);
//Variables
//Strings
final String name;
final String myFormat;
//Others
final Calendar calendar;
final SimpleDateFormat sdf;
final String datePdf;
//Buttons
Button endControlButton;
//TextView
TextView title;
TextView date;
//Edit Text
final EditText oil_TV;
final EditText engine_liquid_TV;
EditText wipers_liquid_TV;
EditText breaks_liquid_TV;
EditText windows_TV;
EditText wipers_TV;
EditText mirrors_TV;
EditText numberplate_TV;
EditText frontTires_TV;
EditText rearTires_TV;
EditText tiresState_TV;
EditText light1_TV;
EditText light2_TV;
EditText light3_TV;
EditText light4_TV;
EditText light5_TV;
EditText light6_TV;
EditText light7_TV;
EditText interiorClean_TV;
EditText exteriorClean_TV;
EditText jacket_TV;
EditText triangle_TV;
EditText strap_TV;
EditText extinguisher_TV;
//Set title text
title = findViewById(R.id.title_TV);
Bundle extras = getIntent().getExtras();
assert extras != null;
name = extras.getString("name");
title.setText(name);
//Display date
date = findViewById(R.id.date_TV);
calendar = Calendar.getInstance();
myFormat = "dd/MM/yy";
sdf = new SimpleDateFormat(myFormat, Locale.FRANCE);
date.setText("Date du contrôle : " + sdf.format(calendar.getTime()));
datePdf = calendar.getTime().toString();
//Variables declaration
oil_TV = findViewById(R.id.oil_TV);
engine_liquid_TV = findViewById(R.id.engine_liquid_TV);
wipers_liquid_TV = findViewById(R.id.wipers_liquid_TV);
breaks_liquid_TV = findViewById(R.id.breaks_liquid_TV);
windows_TV = findViewById(R.id.windows_TV);
wipers_TV = findViewById(R.id.wipers_TV);
mirrors_TV = findViewById(R.id.mirrors_TV);
numberplate_TV = findViewById(R.id.numberplate_TV);
frontTires_TV = findViewById(R.id.frontTires_TV);
rearTires_TV = findViewById(R.id.rearTires_TV);
tiresState_TV = findViewById(R.id.tiresState_TV);
light1_TV = findViewById(R.id.light1_TV);
light2_TV = findViewById(R.id.light2_TV);
light3_TV = findViewById(R.id.light3_TV);
light4_TV = findViewById(R.id.light4_TV);
light5_TV = findViewById(R.id.light5_TV);
light6_TV = findViewById(R.id.light6_TV);
light7_TV = findViewById(R.id.light7_TV);
interiorClean_TV = findViewById(R.id.interiorClean_TV);
exteriorClean_TV = findViewById(R.id.exteriorClean_TV);
jacket_TV = findViewById(R.id.jacket_TV);
triangle_TV = findViewById(R.id.triangle_TV);
strap_TV = findViewById(R.id.strap_TV);
extinguisher_TV = findViewById(R.id.extinguisher_TV);
//Création de listes
final ArrayList textViewArray = new ArrayList(24);
//TextViews
textViewArray.add(oil_TV);
textViewArray.add(engine_liquid_TV);
textViewArray.add(wipers_liquid_TV);
textViewArray.add(breaks_liquid_TV);
textViewArray.add(windows_TV);
textViewArray.add(wipers_TV);
textViewArray.add(mirrors_TV);
textViewArray.add(numberplate_TV);
textViewArray.add(frontTires_TV);
textViewArray.add(rearTires_TV);
textViewArray.add(tiresState_TV);
textViewArray.add(light1_TV);
textViewArray.add(light2_TV);
textViewArray.add(light3_TV);
textViewArray.add(light4_TV);
textViewArray.add(light5_TV);
textViewArray.add(light6_TV);
textViewArray.add(light7_TV);
textViewArray.add(interiorClean_TV);
textViewArray.add(exteriorClean_TV);
textViewArray.add(jacket_TV);
textViewArray.add(triangle_TV);
textViewArray.add(strap_TV);
textViewArray.add(extinguisher_TV);
//Déclaration du bouton Fin de controle
endControlButton = findViewById(R.id.end_control_button);
endControlButton.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetWorldReadable")
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View view) {
//Création du pdf
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(300,600,1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setTextSize(30);
canvas.drawText(name,50,30,paint);
for (int i = 0 ; i<textViewArray.size();i++){
EditText editText = (EditText) textViewArray.get(i);
String editTextDesc = (String) editText.getContentDescription();
String content = editText.getText().toString();
Boolean isEmpty = content.isEmpty();
if (!isEmpty) {
paint.setTextSize(10);
paint.setColor(Color.RED);
canvas.drawText(editTextDesc + " : " + content, 50 , 50 + (20 * i),paint);
} else {
paint.setTextSize(10);
paint.setColor(Color.BLACK);
canvas.drawText(editTextDesc + " : OK",50, 50 + (20 * i),paint);
}
}
document.finishPage(page);
String directory_path = Environment.getExternalStorageDirectory().getPath() + "/ATTM
Vehicules/";
File file = new File(directory_path);
if (!file.exists()){
file.mkdirs();
}
String targetPdf = directory_path + name + datePdf +".pdf";
File filePath = new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
Toast.makeText(getApplicationContext(), "Envoyé", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e("main", "error "+e.toString());
Toast.makeText(getApplicationContext(), "Erreur" + e.toString(), Toast.LENGTH_LONG).show();
}
document.close();
//Mail
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("application/pdf");
shareIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "email#hotmail.fr" });
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "test ");
shareIntent.putExtra(Intent.EXTRA_TEXT, "test");
shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse(targetPdf));
startActivity(shareIntent);
}
});
}
}
Any help would be appreciated. Thanks for reading!
Try the below code in your Activity..
package com.example.pdfshare;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.content.FileProvider;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfDocument.Page;
import android.graphics.pdf.PdfDocument.PageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintAttributes.Margins;
import android.print.PrintAttributes.Resolution;
import android.print.pdf.PrintedPdfDocument;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity implements Runnable {
private Intent mShareIntent;
private OutputStream os;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** PDF Gen should run in own thread to not slow the GUI */
public void makeAndSharePDF(View buttonSource) {
new Thread(this).start();
}
public void run() {
// Create a shiny new (but blank) PDF document in memory
// We want it to optionally be printable, so add PrintAttributes
// and use a PrintedPdfDocument. Simpler: new PdfDocument().
PrintAttributes printAttrs = new PrintAttributes.Builder().
setColorMode(PrintAttributes.COLOR_MODE_COLOR).
setMediaSize(PrintAttributes.MediaSize.NA_LETTER).
setResolution(new Resolution("zooey", PRINT_SERVICE, 300, 300)).
setMinMargins(Margins.NO_MARGINS).
build();
PdfDocument document = new PrintedPdfDocument(this, printAttrs);
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(300, 300, 1).create();
// create a new page from the PageInfo
Page page = document.startPage(pageInfo);
// repaint the user's text into the page
View content = findViewById(R.id.textArea);
content.draw(page.getCanvas());
// do final processing of the page
document.finishPage(page);
// Here you could add more pages in a longer doc app, but you'd have
// to handle page-breaking yourself in e.g., write your own word processor...
// Now write the PDF document to a file; it actually needs to be a file
// since the Share mechanism can't accept a byte[]. though it can
// accept a String/CharSequence. Meh.
try {
File pdfDirPath = new File(getFilesDir(), "pdfs");
pdfDirPath.mkdirs();
File file = new File(pdfDirPath, "pdfsend.pdf");
Uri contentUri = FileProvider.getUriForFile(this, "com.example.fileprovider", file);
os = new FileOutputStream(file);
document.writeTo(os);
document.close();
os.close();
shareDocument(contentUri);
} catch (IOException e) {
throw new RuntimeException("Error generating file", e);
}
}
private void shareDocument(Uri uri) {
mShareIntent = new Intent();
mShareIntent.setAction(Intent.ACTION_SEND);
mShareIntent.setType("application/pdf");
// Assuming it may go via eMail:
mShareIntent.putExtra(Intent.EXTRA_SUBJECT, "Here is a PDF from PdfSend");
// Attach the PDf as a Uri, since Android can't take it as bytes yet.
mShareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(mShareIntent);
return;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
The above code is self explanatory with comments.. All the Best..

How to read a CSV file?

I am creating an application where i do some real-time image analysis and store them into a csv file. The csv has 2 columns time and y-value of each frame.
I want to read this file and store the values from 2 columns into to double array. I want this because i want to perform an fast Fourier transformation on the data.
public class MainActivity extends AppCompatActivity implements CameraView.PreviewReadyCallback {
private static Camera camera = null;
private CameraView image = null;
private LineChart bp_graph;
private int img_Y_Avg, img_U_Avg, img_V_Avg;
private long end = 0, begin = 0;
double valueY, valueU, valueV;
Handler handler;
private int readingRemaining = 1200;
private static long time1, time2, timeDifference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
bp_graph = (LineChart)findViewById(R.id.graph);
graph_features();
//open camera
try {
camera = Camera.open();
handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
camera.stopPreview();
camera.release();
}
};
handler.postDelayed(runnable, 30000);
} catch (Exception e) {
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
}
if (camera != null) {
image = new CameraView(this, camera);
FrameLayout camera_view = (FrameLayout) findViewById(R.id.camera_view);
camera_view.addView(image);
image.setOnPreviewReady(this);
}
}
#Override
protected void onResume(){
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onPreviewFrame(long startTime, int ySum, int uSum, int vSum, long endTime) {
begin = startTime;
img_Y_Avg = ySum;
img_U_Avg = uSum;
img_V_Avg = vSum;
end = endTime;
showResults(begin, img_Y_Avg, img_U_Avg, img_V_Avg, end);
}
private void showResults(long startTime, int ySum, int uSum, int vSum, long endTime){
//set value of Y on the text view
TextView valueOfY = (TextView)findViewById(R.id.valueY);
//valueY = img_Y_Avg;
valueOfY.setText(String.valueOf(img_Y_Avg));
//start time in milliseconds
long StartDurationInMs = TimeUnit.MILLISECONDS.convert(begin, TimeUnit.MILLISECONDS);
ArrayList<Long> startOfTime = new ArrayList<>();
startOfTime.add(StartDurationInMs);
//store value to array list
ArrayList<Integer> yAverage = new ArrayList<>();
yAverage.add(img_Y_Avg);
//convert to readable format
String readableDate = new SimpleDateFormat("MMM dd,yyyy, HH:mm:ss.SSS").format(EndDurationInMs);
Log.d("Date ", readableDate);
Log.d("time ", String.valueOf(String.valueOf(yAverage.size())));
//store when all array are generated
Log.d("time ", String.valueOf(StartDurationInMs));
ArrayList<Long> getValues = new ArrayList<>();
for(int i = 0; i < yAverage.size(); i++) {
getValues.add(startOfTime.get(i));
getValues.add((long)(yAverage.get(i)));
}
//store the yAverage and start time to csv file
storeCsv(yAverage, getValues);
Log.d("MyEntryData", String.valueOf(getValues));
}
public void storeCsv(ArrayList<Integer>yAverage, ArrayList<Long>getValues){
String filename = "temporary.csv";
//File directoryDownload = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/bpReader";
//File logDir = new File (directoryDownload, "bpReader"); //Creates a new folder in DOWNLOAD directory
File logDir = new File(path);
logDir.mkdirs();
File file = new File(logDir, filename);
FileOutputStream outputStream = null;
try {
file.createNewFile();
outputStream = new FileOutputStream(file, true);
//outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
for (int i = 0; i < yAverage.size(); i += 2) {
outputStream.write((getValues.get(i) + ",").getBytes());
outputStream.write((getValues.get(i + 1) + "\n").getBytes());
//outputStream.write((getValues.get(i + 2) + ",").getBytes());
//outputStream.write((getValues.get(i + 3) + "\n").getBytes());
}
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void readCsv(){
}
}
This is my MainActivity. What I am doing here is getting the data from CameraView class for each frame with the help of an interface that I created. After that im storing the values into a CSV file called temporary.csv.
Issues
I want to read this csv and store the first column(the time) into one double array and the second column(yAverage) into another double array.
I also want to delete the file once i have all the data stored into the into the double array.
How can I do that?
I would suggest youto use an open source library like OpenCSV to get the datafrom the CSV file. When you have the library implemented it's only a matter of iterating through the x and y columns and assign them to an array. With OpenCSV it would look like that. But i would also suggest you an more object orientec approach if the x and y with the same index coords are related to each other.
String csvFile = "/Users/mkyong/csv/country3.csv";
int length = 100; //If you dont know how many entries the csv file has i would suggest to use ArrayList
double[] xCoords = new double[length];
double[] yCoords = new double[length];
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(csvFile));
String[] line;
int i = 0;
while ((line = reader.readNext()) != null) {
xCoords[i] = Double.parseDouble(line[0]);
yCoords[i] = Double.parseDouble(line[1]);
}
} catch (IOException e) {
e.printStackTrace();
}
From the answer given by Lucas, I got the direction to my solution
public void readCsv(){
//set the path to the file
String getPath = Environment.getExternalStorageDirectory() + "/bpReader";
String csvFile = "temporary.csv";
String path = getPath+ "/" + csvFile;
//File file = new File(path, csvFile);
int length = 500;
double[] xCoords = new double[length];
double[] yCoords = new double[length];
CSVReader reader = null;
try {
File myFile = new File (path);
reader = new CSVReader(new FileReader(myFile));
String[] line;
int i = 0;
while ((line = reader.readNext()) != null) {
xCoords[i] = Double.parseDouble(line[0]) ;
yCoords[i] = Double.parseDouble(line[1]);
Log.d("read:: ", "Time: "+String.valueOf(xCoords[i])+" Y: "+String.valueOf(yCoords[i]));
}
myFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
And then i had to add
// https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.6'
to my gradle,, which can be found at MVN repository

Check duplicate editText before writing into .csv

I have several editText in my FirstActivity for CSV:
Button save;
CSV csv;
StringBuffer filePathc;
public final static String EXTRA_MESSAGE = "com.example.mapcard.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_card);
txtName= (EditText) findViewById(R.id.txtName);
txtCompany= (EditText) findViewById(R.id.txtCompany);
txtPhone= (EditText) findViewById(R.id.txtPhone);
txtMobile = (EditText) findViewById(R.id.txtMobile);
txtAddress = (EditText) findViewById(R.id.txtAddress);
txtEmail = (EditText) findViewById(R.id.txtEmail);
txtWebsite = (EditText) findViewById(R.id.txtWebsite);
txtTitle = (EditText) findViewById(R.id.txtTitle);
filePathc = new StringBuffer();
filePathc.append("/sdcard/Android/data/");
file = new File(filePathc+filename.toString());
csv = new CSV(file);
save=(Button)findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
csv.writeHeader(txtName.getText().toString()+ ","
+txtCompany.getText().toString()
+ "," +txtPhone.getText().toString()
+ "," +txtMobile.getText().toString()
+ "," +txtAddress.getText().toString()
+ "," +txtEmail.getText().toString()
+ "," +txtWebsite.getText().toString()
+ "," +txtTitle.getText().toString());
Intent intent = new Intent(NewCard.this, Template.class);
intent.putExtra("name", Name);
intent.putExtra("company", Company);
intent.putExtra("phone", Phone);
intent.putExtra("mobile", Mobile);
intent.putExtra("address", Address);
intent.putExtra("email", Email);
intent.putExtra("website", Website);
intent.putExtra("title", Title);
startActivity(intent);
SecondActivity is to write this data into .csv file:
public class CSV {
private PrintWriter csvWriter;
private File file;
public CSV(File file) {
this.file = file;
}
public void writeHeader(String data) {
try {
if (data != null) {
csvWriter = new PrintWriter(new FileWriter(file, true));
csvWriter.print("\r\n"+",");
csvWriter.print(data);
csvWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}}
File in directory is successfully created and data is inserted. I am trying to check the data like Name or Email, if it is duplicate/already recorded to not save into .csv and warn user with Toast "same data".
I think it is something to do with line:
try {
if (data != null) {
Your helps and suggestions are appreciated. Thank you.
Use following function
public boolean exist(String newData){
try {
FileInputStream fIn = new FileInputStream(file);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
if(aDataRow.contains(newData))//<--check if data exists
return true;
}
txtData.setText(aBuffer);
myReader.close();
} catch (Exception e) {
}
return false;
}
And change your write header function to:
public void writeHeader(String data) {
try {
if (data != null&&!data.isEmpty()&&!exist(data)) {
csvWriter = new PrintWriter(new FileWriter(file, true));
csvWriter.print("\r\n"+",");
csvWriter.print(data);
csvWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
data != null doesnt cover the case that the String is just empty, but not null. So basically you get "" from the textview by calling getText(). adding && !"".equals(data) should fix that problem
UPDATE
Well, there is a difference between an empty, and an uninitalized String. An uninitalized String means you declared it like String a; but nothing further.
If you use editText.getText() the editText will return a String which has been initialized but contains only what is currently in it. So basically if there is nothing in the editext it will return "".
And to sum this up:
String a;
null == "" // false
a == null // true
"".equals(editText.getTExt()) // true if the editext doesnt contain anything

Android: ParsingXMLFiles only gets the values for the first XML

Hi I have designed a File Explorer which I use to show some XML files and depending on the selected one I open one XML or another. Until the moment there is no problem at all and with the help of XMLPullParser I insert the text from the attributes into some ArrayLists. The problem is that IF I go back and I select another XML file these values are the same as the following XML and that happens with the following XMLs. I think that the problem is that the arrayLists don´t get empty once a new instance is called.
Here is how this works:
FileExporer where I show the files and I click on anyone.
public class MainActivity extends ListActivity {
private List<String> item = null;
private List<String> path = null;
private String root;
private TextView myPath;
static File file;
static String texto;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myPath = (TextView)findViewById(R.id.path);
root = Environment.getExternalStorageDirectory().getPath();
getDir(root);
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
if(!file.isHidden() && file.canRead() && (file.getName().endsWith("xml"))){
path.add(file.getPath());
if(file.isDirectory()){
item.add(file.getName() + "/");
}else{
item.add(file.getName());
}
}
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
file = new File(path.get(position));
if (file.isDirectory())
{
if(file.canRead()){
getDir(path.get(position));
}else{
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK", null).show();
}
}else {
file = new File(path.get(position));
file.getName();
XMLPullParser.Parse(this);
texto = XMLPullParserHandler.getA(0);
}
Parseo();
Intent i = new Intent(MainActivity.this, Correccion.class);
startActivity(i);
MainActivity.this.finish();
}
public void Parseo(){
}
public static String fileName(){
return file.getName();
}
public static String getText(){
return texto;
}
}
XMLPullParser: It says the file that need to be read and calls a new isntance of XMLPullParserHandler.
public class XMLPullParser{
static String Fichero;
public static void Parse(Context context){
try {
List<Puntuacion> puntuacion;
XMLPullParserHandler parser = new XMLPullParserHandler();
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, MainActivity.fileName());
FileInputStream iStream = new FileInputStream(yourFile);
puntuacion = parser.parse(iStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
XMLPullParserHandler: I think that here is the problem, when I create and add text to the ArrayLists: For example in this case in ArrayList a
public class XMLPullParserHandler {
List<Puntuacion> puntuaciones;
private Puntuacion puntuacion;
static List<String> nombres = new ArrayList<String>();
static List<String> a = new ArrayList<String>();
private String text;
public XMLPullParserHandler() {
// puntuaciones.clear();
// puntuaciones.removeAll(puntuaciones);
puntuaciones = new ArrayList<Puntuacion>();
;
}
public List<Puntuacion> getPuntuacion() {
return puntuaciones;
}
public List<Puntuacion> parse(InputStream is) {
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
parser.setInput(is, null);
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagname = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase("TEST")) {
// create a new instance of puntuacion
puntuacion = new Puntuacion();
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("TEST")) {
puntuaciones.add(puntuacion);
} else if (tagname.equalsIgnoreCase("NUMERO_ACIERTOS")) {
puntuacion.setValor_Transformado((text));
a.add(text);
Log.i("ii", text);
}
break;
default:
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return puntuaciones;
}
public static String getNombre(int posicion){
String[] ListN = new String[nombres.size()];
ListN = nombres.toArray(ListN);
return ListN[posicion];
}
public static String getA(int posicion){
String[] ListA = new String[a.size()];
ListA = a.toArray(ListA);
return ListA[posicion];
}
}
For example if I have in this case a XML with **<NUMERO_ACIERTOS>1</NUMERO_ACIERTOS>** and after this I read another one with **<NUMERO_ACIERTOS>3</NUMERO_ACIERTOS>** in my UI I only see the value **1** because is the first that has been loaded into the arraylist.
thank you for your time and attention.
No me gustan estos:
static List<String> nombres = new ArrayList<String>();
static List<String> a = new ArrayList<String>();
They should not be static, and probably should be private:
private List<String> nombres;
private List<String> a;
I think they should be created new when you start your parse like this:
public List<Puntuacion> parse(InputStream is) {
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
nombres = new ArrayList<String>();
a = new ArrayList<String>();
try {
¡Buena suerte!

Parsing error in Android

I am storing an array of numbers as string(I get the string from shared preferences) and then trying to parse it.
But when I use parseInt my app crashes. The activity Second is called by Main class.
public class Second extends Activity {
public int[] x = new int[50];
public int[] y = new int[50];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
SharedPreferences data= getSharedPreferences("data",0);
SharedPreferences.Editor editor= data.edit();
StringBuilder str = new StringBuilder();
str.append(data.getString("val", "0")).append(",").append(getIntent().getExtras().getString("thetext"));
String end = str.toString();
editor.putString("val", end);
editor.commit();
//EditText et1= (EditText) findViewById(R.id.editText2);
//et1.
String savedString = data.getString("val", "0");
savedString.replaceAll("\\s","");
String[] st = savedString.split(",");
int i;
for(i=0;i<st.length;i++){
st[i].trim();
Log.d("Debug" , "st["+i+"] = "+st[i]);
x[i] = Integer.valueOf(st[i]);
y[i]=i;}
}
public void lineGraphHandler (View view)
{
LineGraph line = new LineGraph();
Intent lineIntent = line.getIntent(this);
startActivity(lineIntent);
}
}
Where is it going wrong?
Add a line between these
st[i].replaceAll("\\s","");
Log.d("Debug" , "st["+i+"] = "+st[i])
x[i] = Integer.parseInt(st[i]);
and see that if that is a convertible string or there are some letters accidently inserted that can't be converted to int?

Categories

Resources