Trouble Writing to file in java - java

Hey im trying to write to a file but im getting an error on the line where it writes the line that goes into each line of a text file, cant figure it out any help would be greatly appreciated
The Writer Code
.
public static void stuIDWrite() throws IOException
{
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn =stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
writer.close();
i++;
}
The Full Code
import java.io.*;
import java.util.*;
public class StudentMain {
/**
* #param args
*/
//array and sorting variables
public static studentConstructor[] stuArrayOrig = new studentConstructor[23];
private static studentConstructor[] stuArrayIdSort = new studentConstructor[23];
private static studentConstructor[] stuArrayNameSort = new studentConstructor[23];
private static int lineCount = 0;
private static int nElms = 0;
//writer
//studentConstructor variables
public static String fn; //First Name
public static String ln; //Last Name
public static String pn; //Preferred Name
public static int id; //Student Id Number
public static boolean ft;//Full-time Boolean
public static int phn; //Student Phone Number
public static boolean lj;//Loving java Boolean
public static String con;//Continuing
File idSort = new File("stuListSortID.txt");
public static void StuRead()
{
Scanner inFile = null;
try
{
inFile = new Scanner
(new FileReader("Res/students.txt"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
System.out.println("File Not Found");
e.printStackTrace();
}
while (inFile.hasNextLine()){
inFile.useDelimiter(",|\\n"); //breaks the lines into single info
ln = inFile.next();
System.out.println(ln);
fn = inFile.next();
System.out.println(fn);
pn = inFile.next();
System.out.println(pn);
id = inFile.nextInt();
System.out.println(id);
ft = inFile.nextBoolean();
System.out.println(ft);
phn = inFile.nextInt();
System.out.println(phn);
lj = inFile.nextBoolean();
System.out.println(lj);
con = inFile.next();
System.out.println(con);
studentConstructor st = new studentConstructor(ln, fn, pn, id, ft, phn, lj, con);
stuArrayOrig[lineCount] = st;
inFile.nextLine();
System.out.println(stuArrayOrig[lineCount]);
lineCount++;
}
//setting info into other arrays
stuArrayIdSort = stuArrayOrig;
stuArrayNameSort = stuArrayOrig;
System.out.println("orig array length" + stuArrayOrig.length);
System.out.println("id array length" + stuArrayIdSort.length);
System.out.println("name array length" + stuArrayNameSort.length);
System.out.println("number of file lines" + lineCount);
inFile.close();
}
public static void stuIdSort()
{
studentConstructor temp;
boolean sorted = false;
while (sorted == false)
{ sorted=true;
for (int i=0; i<stuArrayIdSort.length-1 ; i++)
{
if(stuArrayIdSort[i].getStuId() > stuArrayIdSort[i+1].getStuId())
{
temp = stuArrayIdSort[i+1];
stuArrayIdSort[i+1] = stuArrayIdSort[i];
stuArrayIdSort[i] = temp;
sorted=false;
}
}
}
for(int i=0; i<stuArrayIdSort.length; i++)
{
int getSC = stuArrayIdSort[i].studentId;
System.out.println("number of swaps " + i+1 +" " +getSC);
}
}
//stuArrayIdSort[i].getStuLastName(),stuArrayIdSort[i].getStuFirstName(),stuArrayIdSort[i].getPrefName(),stuArrayIdSort[i].getStuId(),stuArrayIdSort[i].getFTime(),stuArrayIdSort[i].getPhoneNum(),stuArrayIdSort[i].getLovJava(),stuArrayIdSort[i].getCont()
public static void stuIDWrite() throws IOException
{
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn =stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
writer.close();
i++;
}
}
public static void stuNameSort()
{
}
public static void stuNameWrire()
{
}
}
//lastName, firstName, perName, studentId, fulltime,

Ok, here is what you should do:
What's happening is that you are closing it before it can actually do anything. So, lets move your finally clause to the end of everything:
public static void stuIDWrite() throws IOException
{
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn =stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + ","+ id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
i++;
}
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}

I'm not sure you understand how try...catch...finally works. Here's what you have:
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Res/stuIDSorted.txt")));
} catch (IOException ex) {
// report
} finally {
>>>>>>> **try {writer.close();} catch (Exception ex) {}**
}
int i = 0;
while (i <= stuArrayIdSort.length + 1)
{
//bunch of stuff
writer.write(...);
>>>>>>> **writer.close();**
i++;
}
}
You close writer ONCE before you've even used it (finally block gets executed after the try block), and ONCE inside the loop. So, if somehow the code could make it past the writer.close() in the finally block, it would never make it through the loop more than once.
It is not necessary to close a BufferedWriter. The class makes sure to close it internally.

If you are using Java 7, you might want to consider using the "try-with-resources" syntax, which can simplify a correct implementation of file handling greatly in cases like this. Your original code had some issues, but even the accepted answer has some problems that I believe will result in a NullPointerException in the case where the file can't be opened (unverified).
I think you may also have some problems with your while loop boundary conditions also. I've changed the while loop to the more traditional for loop. Keep in mind that java array elements run from 0 to array.length - 1 inclusive.
public static void stuIDWrite() throws IOException
{
try (FileWriter writer = new FileWriter("Res/stuIDSorted.txt"))
{
for (int i = 0; i < stuArrayIdSort.length; ++i)
{
ln = stuArrayIdSort[i].getStuLastName();
fn = stuArrayIdSort[i].getStuFirstName();
pn = stuArrayIdSort[i].getStuFirstName();
id = stuArrayIdSort[i].getStuId();
ft = stuArrayIdSort[i].getFTime();
phn = stuArrayIdSort[i].getPhoneNum();
lj = stuArrayIdSort[i].getLovJava();
con = stuArrayIdSort[i].getCont();
writer.write(ln + "," + fn + "," + pn + "," + id + "," + ft + "," + phn + "," + lj + "," + con + "\n");
}
}
}
You could also look at using the "enhanced for loop" syntax for the inner loop that may further streamline things.

Related

How do I reopen an account in java, using a constructor with differnt argument lengths?

I want to print the existing balance and name of the account, but when I put the two inside of the arguments it draws an error: args of different lengths. What will make the this.balance and this.nm appear on the form side of the program when I open an existing account?
public abstract class AssetAccount implements Account{
public int AcctNo;
public double balance;
public String actmsg,errmsg;
public String nm, typecd;
public double rate;
NumberFormat c = NumberFormat.getCurrencyInstance();
public AssetAccount(String typecd, String nm, double sbal) {
this.AcctNo = 0;
this.actmsg = "";
this.errmsg = "";
this.balance= 0;
this.typecd = typecd;
while (this.AcctNo == 0) {
try {
this.AcctNo = (int) (Math.random() * 1000000);
BufferedReader in = new BufferedReader(
new FileReader(this.typecd + this.AcctNo + ".txt"));
in.close();
this.AcctNo = 0;
} catch (IOException e) {
//'good' result: account does not yot exist....
this.nm = nm;
this.balance = sbal;
writestatus();
if (this.errmsg.isEmpty()) {
actmsg = this.typecd + "Account " +
this.nm + " " + this.AcctNo + " opened.";
writelog(actmsg);
}
if (!this.errmsg.isEmpty()) {
this.balance = 0;
this.AcctNo = -1;
this.typecd = "";
}
} catch (Exception e) {
errmsg = "Fatal error in Account constructor: " +
e.getMessage();
this.AcctNo = -1;
this.typecd = "";
}
}//end of while
}//end of constructor
public AssetAccount(String typecd, int acctno) {
//constructor for known acct number
errmsg = "";
actmsg = "";
// need to get the balance and name so that it shows when re opened
this.typecd = typecd;
this.AcctNo = acctno;
try {
BufferedReader in = new BufferedReader(
new FileReader( typecd + acctno + ".txt"));
actmsg = this.nm + "Account " + acctno + " re-opened.";
} catch (Exception e) {
errmsg = "Error re-opening account: " + e.getMessage();
this.AcctNo = -1;
}
}
private void writestatus() { //should write status and write log be one method?
try {
PrintWriter out = new PrintWriter(
new FileWriter(this.typecd + this.AcctNo + ".txt"));
out.println(this.nm);
out.println(this.balance);
out.close();
} catch (IOException e) {
errmsg = "Error writing status file for "
+ this.typecd + " account: "+ this.AcctNo;
} catch(Exception e) {
errmsg = "General error in status update: " + e.getMessage();
}
} //end of writestatus

How do you write to a file in java?

This is a code snippet that shows me trying to write to a file.
public void printContents() {
int i = 0;
try {
FileReader fl = new FileReader("Product List.txt");
Scanner scn = new Scanner(fl);
while (scn.hasNext()) {
String productName = scn.next();
double productPrice = scn.nextDouble();
int productAmount = scn.nextInt();
System.out.println(productName + " is " + productPrice + " pula. There are " + productAmount + " items left in stalk.");
productList[i] = new ReadingAndWritting(productName, productPrice, productAmount);
i = i + 1;
}
scn.close();
} catch (IOException exc) {
exc.printStackTrace();
} catch (Exception exc) {
exc.printStackTrace();
}
}
public void writeContents() {
try {
//FileOutputStream formater = new FileOutputStream("Product List.txt",true);
Formatter writer = new Formatter(new FileOutputStream("Product List.txt", false));
for (int i = 0; i < 2; ++i) {
writer.format(productList[i].name + "", (productList[i].price + 200.0 + ""), (productList[i].number - 1), "\n");
}
writer.close();
} catch (Exception exc) {
exc.printStackTrace();
}
}
The exception thrown while trying to run this code is:
java.util.NoSuchElementException at ReadingAndWritting.printContents(ReadingAndWritting.java:37).
I tried multiple things and only ended up with: "cokefruitgushersAlnassma" in the file. What I want is:
coke 7.95 10
fruitgushers 98.00 6
Alnassma 9.80 7
The Problem seems to be in
String productName = scn.next();
// Here:
double productPrice = scn.nextDouble();
// And here:
int productAmount = scn.nextInt();
After scn.next(), you don't check if scn.hasNext() before requesting the next element (double or int, respectively). So, either your file is not complete, or not in the exact structure you expect, or you just missed the two additional checks before trying to work with data which just isn't there.
Solution could be like:
while (scn.hasNext()) {
String productName = scn.next();
if ( scn.hasNext() ) {
double productPrice = scn.nextDouble();
if ( scn.hasNext() ) {
int productAmount = scn.nextInt();
// Do something with the three values read...
} else {
// Premature end of file(?)
}
} else {
// Premature end of file(?)
}
}

How to get the value if resultset matched with the entire row value?

Here I attached my code. When if stateVector contains the statename I need to check the that entire row only, not all the icd and dicd vector value. How I need to do that?
In my code its checking all vectors once the statename matched with any other or icdid it's showing it's available.
public class LCDEdits
{
#SuppressWarnings("unchecked")
public String validateICD_CPT(String cptCode, String stateName, String icdCode) throws Exception
{
/**** Variable Initialization ***/
String lcdRes = null;
StringBuffer lcdSql = null;
// String error = null;
java.sql.Connection con = null;
java.sql.PreparedStatement poStmt1 = null;
DBConfig db1 = null;
ResultSet rs = null;
JSONObject JObj = new JSONObject();
try
{
lcdSql = new StringBuffer(" SELECT cpt.hcpc_code, cpt.lcd_id, statepri.state_abbr, icd.icd10_id, ");
lcdSql.append(" dicd.icd10_id_dont FROM lcd_cpt cpt ");
lcdSql.append(" LEFT JOIN lcd_statepri statepri ON(cpt.lcd_id = statepri.lcd_id) ");
//lcdSql.append(" LEFT JOIN lcd_statesec statesec ON( cpt.lcd_id = statesec.lcd_id) ");
lcdSql.append(" LEFT JOIN lcd_icd_support icd ON( cpt.lcd_id = icd.lcd_id) ");
lcdSql.append(" LEFT JOIN lcd_icd_dont_support dicd ON( cpt.lcd_id = dicd.lcd_id) ");
lcdSql.append(" WHERE hcpc_code = ? ");
db1 = new DBConfig();
con = db1.openConn();
poStmt1 = con.prepareStatement(lcdSql.toString());
poStmt1.setString(1, cptCode);
rs = poStmt1.executeQuery();
Vector<String> stateVector = new Vector<String>();
Vector<String> icdVector = new Vector<String>();
Vector<String> dicdVector = new Vector<String>();
while(rs.next())
{
stateVector.add(rs.getString("state_abbr") );
// icdVector.add(rs.getString("icd10_id") );
// dicdVector.add(rs.getString("icd10_id_dont") );
//stateVector.add(rs.getString("sec_state_abbr") );
}
if(stateVector.contains(stateName))
{
if(icdVector.contains(icdCode))
{
// String lcd_icd = lcd_Id;
lcdRes = "CPT-Code is Available in LCD Database.";
// lcdRes1 = "As for the LCD-Code " +lcd_icd+ ", the CPT-Code " + cptCode + " is supported the Diagnosis " +icdCode+ " in the state of " +stateName+ ".";
}
else if(dicdVector.contains(icdCode))
{
lcdRes = "Medicare is not interest to pay Amount for this CPT-Code.";
// lcdRes1 = "As for the LCD-Code " +lcd_Id+ ", the CPT-Code " +cptCode+ " is not supported the Diagnosis " +icdCode+ " in the state of " +stateName+ ".";
}
else
{
lcdRes = "CPT-Code is not available in the LCD-Database.";
// lcdRes1 = "As for the LCD-Code " +lcd_Id+ ", the CPT-Code " +cptCode+ " is not applicable for the Diagnosis " +icdCode+ " in the state of " +stateName+ ".";
}
}
else
{
// String lcd_state = lcd_Id;
lcdRes = "State not matched with LCD-Code.";
// lcdRes1 = "As for the LCD-Code " +lcd_state+ ", the CPT-Code " +cptCode+ " is not applicable in the state of " +stateName+ ".";
}
JObj.put("status", "success");
JObj.put("res_msg", lcdRes);
// JObj.put("dis_msg", lcdRes1);
}
catch(Exception ex) {
ex.printStackTrace();
JObj.put("status", "failed");
}
finally {
rs.close();
poStmt1.close();
db1.closeConnection(con);
}
return JObj.toString();
}
}
First, separate the reading from the database and the processing of the data.
Vector stateVector = null;
try {
Reading data from database
} catch (the problems) {
And handle them
} finally {
close the connection
}
then check if you have some data:
if (stateVector != null {
// get the data you want, probably with a loop construct
}

Android SQLite cursor returns 33 results, but debug only outputs 17

Hi folks I've got a strange cade. I'm trying to debug the SQLite DB in an app. If I do a query SELECT * from table I get 33 results, but if I iterate over the cursor it ends at result #17.
Here's my debug class (the method in question is public static void WriteToFile(Cursor cursor, String query , String tables, String uri)) :
package com.s2u.android.ps;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;
import com.s2u.android.ps.BO.App;
import com.s2u.android.ps.BO.AppMember;
import com.s2u.android.ps.datamodel.DatabaseManager;
import com.s2u.android.ps.networkApis.AndroidLog;
import com.s2u.android.ps.networkApis.AppConfig;
public class DebugToFile {
private static String TAG = "DebugToFile";
private static File path = new File(Environment.getExternalStorageDirectory() + "/ps_debug");
public static void WriteToFile(String lines , String tag)
{
WriteToFile(lines , tag , "txt");
}
public static void WriteToFile(String lines , String tag , String ext)
{
if (!Validate("WriteToFile(String lines)"))
return;
File file = new File(path, tag + "_" + GetDateStampTens() + "." + ext);
try
{
FileWriter fw = new FileWriter(file.getAbsolutePath() , true);
PrintWriter pw = new PrintWriter(fw);
pw.println(GetDateStamp() + " - " + lines);
pw.println();
pw.flush();
pw.close();
//Log.e(TAG, "WriteToFile(String lines) - " + file.toString());
}
catch (Exception e)
{
Log.e(TAG, "WriteToFile(String lines) failed!", e);
}
}
public static void WriteToFileAppMember(ArrayList<AppMember> appMembers , String tag)
{
if (!Validate("WriteToFile(AppMember)"))
return;
File file = new File(path, tag + "_" + GetDateStampTens() + ".csv");
try
{
FileWriter fw = new FileWriter(file.getAbsolutePath() , true);
PrintWriter pw = new PrintWriter(fw);
pw.println(GetDateStamp() + " - " + "AppMembers");
boolean doOnce = true;
for(com.s2u.android.ps.BO.AppMember appMember : appMembers)
{
if (doOnce)
{
doOnce = false;
pw.println(appMember.getCsvLabels());
}
pw.println(appMember.getCsvString());
}
pw.println();
pw.flush();
pw.close();
//Log.e(TAG, "WriteToFile(String lines) - " + file.toString());
}
catch (Exception e)
{
Log.e(TAG, "WriteToFile(String lines) failed!", e);
}
}
public static void WriteToFileAppMember(List<AppMember> appMembers , String tag)
{
if (!Validate("WriteToFile(AppMember)"))
return;
File file = new File(path, tag + "_" + GetDateStampTens() + ".csv");
try
{
FileWriter fw = new FileWriter(file.getAbsolutePath() , true);
PrintWriter pw = new PrintWriter(fw);
pw.println(GetDateStamp() + " - " + "AppMembers");
boolean doOnce = true;
for(com.s2u.android.ps.BO.AppMember appMember : appMembers)
{
if (doOnce)
{
doOnce = false;
pw.println(appMember.getCsvLabels());
}
pw.println(appMember.getCsvString());
}
pw.println();
pw.flush();
pw.close();
//Log.e(TAG, "WriteToFile(String lines) - " + file.toString());
}
catch (Exception e)
{
Log.e(TAG, "WriteToFile(String lines) failed!", e);
}
}
public static void WriteToFileApps(List<App> apps , String tag)
{
if (!Validate("WriteToFile(AppMember)"))
return;
File file = new File(path, tag + "_" + GetDateStampTens() + ".csv");
try
{
FileWriter fw = new FileWriter(file.getAbsolutePath() , true);
PrintWriter pw = new PrintWriter(fw);
pw.println(GetDateStamp() + " - " + "App objects");
boolean doOnce = true;
for(com.s2u.android.ps.BO.App app : apps)
{
if (doOnce)
{
doOnce = false;
pw.println(app.getCsvLabels());
}
pw.println(app.getCsvString());
}
pw.println();
pw.flush();
pw.close();
//Log.e(TAG, "WriteToFile(String lines) - " + file.toString());
}
catch (Exception e)
{
Log.e(TAG, "WriteToFile(String lines) failed!", e);
}
}
public static void WriteToFile(Cursor cursor, String query , String tables, String uri)
{
if (!Validate("WriteToFile(cursor)"))
return;
File file = new File(path, uri + "_" + GetDateStampTens() + ".csv");
try
{
FileWriter fw = new FileWriter(file.getAbsolutePath(), true);
PrintWriter pw = new PrintWriter(fw);
int resultCount = cursor.getCount();
pw.println("time: " + GetDateStamp());
pw.println("tables: " + tables);
pw.println("query: " + query);
pw.println("result count: " + Integer.toString(resultCount));
int row = 0;
String labels = "row,";
int startPosition = cursor.getPosition();
cursor.moveToPosition(-1);
while (cursor.moveToNext())
{
int colCount = cursor.getColumnCount();
row++;
if (row >= resultCount)
{
pw.println("Error! rows >= cursor count -- at row : " + Integer.toString(row) );
break;
}
StringBuilder line = new StringBuilder(512);
if (colCount <= 0)
pw.println("Empty row?");
for(int i = 0; i < colCount; i++)
{
if (row == 1)
{
labels += cursor.getColumnName(i) + "[" + GetCursorFieldTypeString(cursor, i) + "]";
if (i < colCount - 1)
labels += ",";
}
if (i == 0)
line.append(Integer.toString(row) + ",");
line.append(GetCursorString(cursor, i));
if (i < colCount - 1)
{
line.append(",");
}
}
if (row == 1)
pw.println(labels);
pw.println(line.toString());
cursor.moveToNext();
if (row > 100)
{
pw.println("max rows output - stopped at row: " + Integer.toString(row));
break;
}
}
pw.println("END");
pw.println();
pw.flush();
pw.close();
//Log.e(TAG, "WriteToFile(cursor) - " + file.toString());
cursor.moveToPosition(startPosition);
}
catch (Exception e)
{
Log.e(TAG, "WriteToFile(cursor) failed!", e);
}
}
private static boolean Validate(String methodName)
{
if (!AppConfig.isTestBuild())
{
Log.i(TAG, methodName + " - this is not a test build!");
return false;
}
if (!isExternalStorageWritable())
{
AndroidLog.e(TAG, methodName + " - external storage not accessible");
return false;
}
if (!path.exists())
{
path.mkdir();
if (!path.exists())
{
AndroidLog.e(TAG, methodName + " - directory doesn't exist and couldn't create it: " + path.toString());
return false;
}
}
return true;
}
private static String GetDateStamp()
{
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd-kk:mm:ss.SSS");
String date = df.format(c.getTime());
return date;
}
private static String GetDateStampTens()
{
String date = GetDateStamp();
date = date.substring(0,date.length() - 1) + "0";
return date;
}
private static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
private static String GetCursorString(Cursor cursor, Integer i)
{
String result = "undefined";
switch(cursor.getType(i))
{
case Cursor.FIELD_TYPE_NULL:
result = "NULL";
break;
case Cursor.FIELD_TYPE_BLOB:
result = "BLOB length: " + Integer.toString(cursor.getBlob(i).length);
break;
case Cursor.FIELD_TYPE_FLOAT:
result = Float.toString(cursor.getFloat(i));
break;
case Cursor.FIELD_TYPE_INTEGER:
result = Integer.toString(cursor.getInt(i));
break;
case Cursor.FIELD_TYPE_STRING:
result = cursor.getString(i);
break;
default:
result = "undefined cursor value type(" + Integer.toString(cursor.getType(i)) + ") -- try getString: " + cursor.getString(i);
}
result.replace("", " ");
return result;
}
private static String GetCursorFieldTypeString(Cursor cursor, Integer i)
{
String result = "UNK";
switch(cursor.getType(i))
{
case Cursor.FIELD_TYPE_NULL:
result = "NULL";
break;
case Cursor.FIELD_TYPE_BLOB:
result = "BLOB";
break;
case Cursor.FIELD_TYPE_FLOAT:
result = "F";
break;
case Cursor.FIELD_TYPE_INTEGER:
result = "INT";
break;
case Cursor.FIELD_TYPE_STRING:
result = "STR";
break;
default:
result = "UNK(" + Integer.toString(cursor.getType(i)) + ") ";
}
return result;
}
public static String AppListTypeToString(int appListType)
{
if (appListType == 0)
return "kAppListMain";
else if (appListType == 1)
return "kAppListProfile";
else if (appListType == 2)
return "kAppListPromoted";
return "unknown list type int: " + Integer.toString(appListType);
}
public static void DumpDatabaseToFiles(DatabaseManager db)
{
SQLiteDatabase readableDb = db.getReadableDatabase();
DumpDatabaseToFiles(readableDb);
}
public static void DumpDatabaseToFiles(SQLiteDatabase db)
{
if (!Validate("DumpDatabaseToFiles"))
return;
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
if (c.getCount() <= 0)
{
WriteToFile("table name count: " + Integer.toString(c.getCount()) , "dbdump_err");
c.close();
return;
}
//AndroidLog.i(TAG , "DumpDB table count: " + Integer.toString(c.getCount()));
List<String> tableNames = new ArrayList<String>();
if (c.moveToFirst())
{
while(!c.isAfterLast())
{
tableNames.add(c.getString(c.getColumnIndex("name")));
c.moveToNext();
}
}
c.close();
for (int i = 0; i < tableNames.size(); i++)
{
String table = tableNames.get(i);
c = db.rawQuery("SELECT * FROM " + table + " LIMIT 100 ", null);
WriteToFile(c, "all" , table, table);
c.close();
}
}
}
The output csv file is:
tables: app - from AppDAO.bulkInsertApp
query: SELECT * FROM app
result count: 33
row,_id[INT],packageName[STR],appName[STR],iconUrl1[STR],iconUrl2[NULL],publisher[STR],publisherEmail[NULL],price[INT],currency[STR],version[STR],category[STR],releaseDate[NULL],updatedOn[NULL],hasTried[INT],promo_url[NULL],promoParam[NULL],promoValueKey[NULL]
1,8192,com.shared2you.android.powerslyde,Powerslyde,https://lh5.ggpht.com/1qigt9Zz7oh5kTFiIS9ukJljVTm7W-Ur34XzcaQhFjc9GlMzATJ-ATRwYB6gxQhscHEU=w300,NULL,Shared2you, Inc.,NULL,0,, 1.08 ,Lifestyle,NULL,NULL,1,NULL,NULL,NULL
2,8219,com.android.providers.downloads.ui,com.android.providers.downloads.ui,NULL,NULL,NULL,NULL,NULL,,NULL,NULL,NULL,NULL,1,NULL,NULL,NULL
3,8225,com.google.android.apps.maps,Maps,https://lh3.ggpht.com/JW-F0fkeBHpKyh8lDcyQ7CveTRynYGByVBH9hUqnJxw4x64ORhoFJISdOWhekULemw0=w300,NULL,Google Inc.,NULL,0,, Varies with devic,Travel & Local,NULL,NULL,1,NULL,NULL,NULL
4,8231,com.android.vending,com.android.vending,NULL,NULL,NULL,NULL,NULL,,NULL,NULL,NULL,NULL,1,NULL,NULL,NULL
5,8246,com.google.android.apps.magazines,Google Play Newsstand,https://lh5.ggpht.com/rowOPaiODov-bNG7rnD6awPZwLnOc7Vzab-29GpfvB6jfE8DhOR42owBqAmLUXj-W2sI=w300,NULL,Google Inc.,NULL,0,, 3.1.0 ,News & Magazines,NULL,NULL,1,NULL,NULL,NULL
6,8248,com.google.android.gm,Gmail,https://lh4.ggpht.com/Ebn-CW55BnkwG7ng5nuGpijVpJeabTa-uPijd4keKbHpedz29SvDj3EZkfr20ZZzznE=w300,NULL,Google Inc.,NULL,0,, Varies with devic,Communication,NULL,NULL,1,NULL,NULL,NULL
7,8250,com.google.android.music,Google Play Music,https://lh6.ggpht.com/5opWBg-m6yFcjWzJz1LlT05YIf2Alyiy9YtpQm1f6U42LXWmCvB54M1zEkV9-hCaoTc=w300,NULL,Google Inc.,NULL,0,, Varies with devic,Music & Audio,NULL,NULL,1,NULL,NULL,NULL
8,8253,com.google.android.videos,Google Play Movies & TV,https://lh5.ggpht.com/fFPQTALNNU4xflvbazvbwPL5o4X3a_CqYHUWIh4FXmfU78aSSuP1OMkGXhXouxXzWPov=w300,NULL,Google Inc.,NULL,0,, Varies with devic,Media & Video,NULL,NULL,1,NULL,NULL,NULL
9,8312,com.android.chrome,Chrome Browser - Google,https://lh6.ggpht.com/lum4KYB0TtgvR-8vRMUZ_JhRnMQ4YqBIR0yjspc4ETsM9iJ8-4YHZ0s0HO9i0ez_=w300,NULL,Google Inc.,NULL,0,, Varies with devic,Communication,NULL,NULL,1,NULL,NULL,NULL
10,8316,com.google.android.calendar,Google Calendar,https://lh5.ggpht.com/qgUPYBPSTb61cPrijI9YXV3BEy00t5bhoBugDpEXTdEsQEv9B9-j8_ZDs_ClQzPbskc=w300,NULL,Google Inc.,NULL,0,, 201308023 ,Productivity,NULL,NULL,1,NULL,NULL,NULL
11,8433,com.estrongs.android.pop,ES File Explorer File Manager,https://lh5.ggpht.com/P31CiAbF5UMC1wbJxv2sPT4tSLLqfqUZPp8N0ATEaA0ZeMxXv_NjVDiswVKjeUUSS2w=w300,NULL,ES APP Group,NULL,0,, Varies with devic,Productivity,NULL,NULL,1,NULL,NULL,NULL
12,8867,com.devhd.feedly,Feedly,https://lh4.ggpht.com/rkouDgWbT3WNztDRa5QvnN8SatDK3zeHHwOMHZbiu2Vlf3-9hLlmH89W9gJpGEtxo3U=w300,NULL,Feedly Team,NULL,0,, 18.1.2 ,News & Magazines,NULL,NULL,1,NULL,NULL,NULL
13,8917,com.google.android.email,com.google.android.email,NULL,NULL,NULL,NULL,NULL,,NULL,NULL,NULL,NULL,1,NULL,NULL,NULL
14,12113,com.google.android.play.games,Google Play Games,https://lh5.ggpht.com/tkg8ndU21RjzO5WSz7JRpYJ35P-oDTm0md2sNwvVoBtQ0kE_ORHhorrzQWcjVTevxP8_=w300,NULL,Google Inc.,NULL,0,, 1.1.04 ,Entertainment,NULL,NULL,1,NULL,NULL,NULL
15,87853,com.google.android.apps.docs.editors.sheets,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,1,NULL,NULL,NULL
16,87862,com.google.android.apps.photos,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,1,NULL,NULL,NULL
17,87867,com.umfersolutions.eatthiszombies,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,1,NULL,NULL,NULL
END
Thanks!
You are advancing the cursor position two times, one in
while (cursor.moveToNext())
and the other one at the end of the loop in
pw.println(line.toString());
cursor.moveToNext();
Thats why you always will get half of the results, since at the end you move it one position, and then at then when checking the while condition it will advance again, so its reading position 0, then position 2, then 4...and so on...
Duplicate cursor.moveToNext() in the loop:
while (cursor.moveToNext())
{
...
pw.println(line.toString());
cursor.moveToNext();
...
}

Error. BufferedWriter repeating lines at end of file

I have here an error and dont know what is happening.
My class gets a vector of hashmaps and a rute, and then write that hashmap to a file in that route.
This is the code:
/* Variables de entrada */
Vector vecHm = (Vector) context.getAttribute(sVecHashmap);
String strFileLocation = "" + context.getAttribute(sFileLocation);
// Inicializamos variables
FileWriter fileWriter = null;
BufferedWriter bufferedWriter = null;
try
{
fileWriter = new FileWriter(strFileLocation,true);
bufferedWriter = new BufferedWriter(fileWriter);
String linea = "";
String lineaCabecera = "";
for (int i=0;i<vecHm.size();i++)
{
HashMap hm = (LinkedHashMap) vecHm.get(i);
Iterator it = hm.entrySet().iterator();
linea = "";
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry)it.next();
if (i==0)
{
if (lineaCabecera.equals("") == false)
{
lineaCabecera = lineaCabecera + ";";
}
lineaCabecera = lineaCabecera + (String)pairs.getKey();
}
if (linea.equals("") == false)
{
linea = linea + ";";
}
linea = linea + (String)pairs.getValue();
//it.remove(); // avoids a ConcurrentModificationException
}
System.out.println("PRF:: HashmapToFile:: Iteracion: " + i + ". Linea: " + linea);
if (i==0)
{
System.out.println("PRF:: Pinto Cabecera. ");
bufferedWriter.write(lineaCabecera);
bufferedWriter.newLine();
//bufferedWriter.write('\n');
}
bufferedWriter.write(linea);
bufferedWriter.newLine();
//bufferedWriter.write('\n');
}
} catch (Exception e)
{
e.printStackTrace();
throw new WFException(" ERROR writing the file");
} finally
{
try
{
// Cerramos el fichero
bufferedWriter.close();
fileWriter.close();
} catch (Exception e)
{
e.printStackTrace();
throw new WFException(" ERROR closing the file");
}
}
I have a trace that show me the line to write in the file:
System.out.println("PRF:: HashmapToFile:: Iteracion: " + i + ". Linea: " + linea);
The log that i see is this (i will put only the last four iterations):
PRF:: HashmapToFile:: Iteracion: 90. Linea: eufekeptuil;null;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo
PRF:: HashmapToFile:: Iteracion: 91. Linea: hwukbzakmfuutrhnfzm;null;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo
PRF:: HashmapToFile:: Iteracion: 92. Linea: Securitas Europe;29-JAN-15;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo
PRF:: HashmapToFile:: Iteracion: 93. Linea: Tarifa New 544;05-FEB-15;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo
But... when i see the file... i have this at the end:
Securitas Europe;29-JAN-15;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo -OK. Perfect-
Tarifa New 544;05-FEB-15;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo -OK. Perfect-
And then:
N-15;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo (repeated and unfinished line)
Tarifa New 60;15-JAN-15;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo (repeated line)
vjvrqgxavk;null;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo;Inactivo (repeated line)
And another 15 more lines repeated.
Any clue?
Thanks all
Forget the problem. The files are good. The problem is in the downloader. The system is putting more data in that functionality.

Categories

Resources