Why do I get a "no such table error" when working with SQLite in Android Studio, even though it works fine with another table in the same condition? - java

I am programming a quiz app in android studio. One of my classes (all the other classes work perfectly) is called "Geschichte":
package com.example.integrationsquiz;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
import java.util.stream.IntStream;
public class Geschichte extends AppCompatActivity implements View.OnClickListener {
ImageView gBild;
TextView frage, auswertung;
Button antwortA, antwortB, antwortC, antwortD;
Button [] knoepp = {antwortA, antwortB, antwortC, antwortD};
int laenge = 3;
ArrayList<Integer> schongefragt = new ArrayList<Integer>();
Button rButton;
// First SQLite Table, here it works perfectly
final String gdbName = "histoerche.db";
final String gdbTabelle = "geschichtsfragen";
// Second SQLite Table, this fails
final String wndNAME = "wnd.db";
final String wndTabelle = "wnd";
int aw;
String imageName;
Button weiter;
boolean gedruckt;
int korrekt;
int color;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geschichte);
gBild = findViewById(R.id.gBild);
frage = findViewById(R.id.frage);
antwortA = findViewById(R.id.antwortA);
antwortB = findViewById(R.id.antwortB);
antwortC = findViewById(R.id.antwortC);
antwortD = findViewById(R.id.antwortD);
auswertung = findViewById(R.id.auswertung);
weiter = findViewById(R.id.wigger);
holeGeschichtsDatenbank();
fragestellen();
antwortA.setOnClickListener(this);
antwortB.setOnClickListener(this);
antwortC.setOnClickListener(this);
antwortD.setOnClickListener(this);
weiter.setOnClickListener(this);
}
public void holeGeschichtsDatenbank(){
//Tables are only created if app is installed for the first time
if (MainActivity.installation==true){
//Declaring and initializing first table
SQLiteDatabase gdb = openOrCreateDatabase(gdbName, MODE_PRIVATE, null);
gdb.execSQL("CREATE TABLE " + gdbTabelle + "(id INTEGER, fragentext TEXT, bild String, rAntwort TEXT, kat Text)");
gdb.execSQL("INSERT INTO " + gdbTabelle + " VALUES(1, 'Wann fand die Wiedervereinigung statt?', 'wvg', '03.10.1990', 'WND')");
gdb.execSQL("INSERT INTO " + gdbTabelle + " VALUES(2, 'Wann fand die Reichsgründung statt?', 'reichsg', '18.01.1871', '187080')");
gdb.execSQL("INSERT INTO " + gdbTabelle + " VALUES(3, 'Wann trat das Grundgesetz inkraft?', 'gg', '23.05.1949', '4050')");
//Declaring and initializing second table
SQLiteDatabase wnd = openOrCreateDatabase(wndNAME, MODE_PRIVATE, null);
wnd.execSQL("CREATE TABLE " + wndTabelle + "(id INTEGER, antwort TEXT)");
wnd.execSQL("INSERT INTO "+ wndTabelle + " VALUES(1,'09.11.1989')");
wnd.execSQL("INSERT INTO "+ wndTabelle+ " VALUES(2,'17.06.1990')");
wnd.execSQL("INSERT INTO "+ wndTabelle + " VALUES(3,'01.01.1990')");
wnd.execSQL("INSERT INTO "+ wndTabelle + " VALUES(4,'02.03.1990')");
gdb.close();
wnd.close();
}
}
protected void fragestellen(){
//This method is not relevant for my problem, it works perfectly.
auswertung.setText("Fabelhaft");
auswertung.setTextColor(Color.WHITE);
gedruckt = false;
weiter.setVisibility(View.VISIBLE);
int ind = (int)(Math.random() * laenge)+1;
if (schongefragt.size()!=laenge){
antwortA.setBackgroundColor(Color.MAGENTA);
antwortB.setBackgroundColor(Color.MAGENTA);
antwortC.setBackgroundColor(Color.MAGENTA);
antwortD.setBackgroundColor(Color.MAGENTA);
antwortA.setText("Antwort A");
antwortB.setText("Antwort B");
antwortC.setText("Antwort C");
antwortD.setText("Antwort D");
//Now choosing random question
while (schongefragt.contains(ind)){
ind = (int)(Math.random() * laenge)+1;
}
schongefragt.add(ind);
setzefrage(ind);
}
}
#SuppressLint("ResourceType")
protected void setzefrage(int j){
if (j <=laenge){
//Recalling the first database and selecting values, this works fine.
SQLiteDatabase db = openOrCreateDatabase(gdbName, MODE_PRIVATE, null );
Cursor cursor = db.rawQuery("SELECT * FROM " + gdbTabelle+ " WHERE id = ' " + j + " ' " , null);
cursor.moveToFirst();
frage.setText(cursor.getString(1));
imageName = cursor.getString(2);
int imageID = getResources().getIdentifier(imageName, "drawable", getPackageName());
gBild.setImageResource(imageID);
aw = (int) (Math.random()*4) +1;
/* The first database contains all the questions with the right answer, it is
now placing the right answer on a randomly chosen button.
*/
switch (aw){
case 1:
antwortA.setText(cursor.getString(3));
rButton = antwortA;
break;
case 2:
antwortB.setText(cursor.getString(3));
rButton = antwortB;
break;
case 3:
antwortC.setText(cursor.getString(3));
rButton = antwortC;
break;
case 4:
antwortD.setText(cursor.getString(3));
rButton = antwortD;
break;
}
if(j==1){
/*Now here I try to place the texts saved in the second database
on the buttons (if the program selects the first question) I do the same
thing as above but it does not work*/
try{
//Kategorie k = new Kategorie();
for (int i = 0; i < 4; i++) {
if (knoepp[i] != rButton) {
SQLiteDatabase db2 = openOrCreateDatabase(wndNAME, MODE_PRIVATE, null);
Cursor cursor2 = db2.rawQuery("SELECT * FROM " + wndTabelle + " WHERE id = ' " + (i+1) + " ' ", null);
cursor2.moveToFirst();
knoepp[i].setText(cursor2.getString(1));
cursor2.close();
db2.close();
}
}
}catch(Exception e){
frage.setTextSize(15);
frage.setText(e.getMessage());
System.out.println(e.getMessage());
}
}
cursor.close();
db.close();
}
}
#Override
public void onClick(View view) {
// This method checks if the answer is correct. It works perfectly
switch (view.getId()){
case R.id.antwortA:
if (aw ==1){
if (gedruckt == false) {
antwortA.setBackgroundColor(Color.GREEN);
korrekt = korrekt + 1;
auswertung.setTextColor(Color.BLACK);
gedruckt = true;
}
}else{
if(gedruckt==false){
antwortA.setBackgroundColor(Color.RED);
rButton.setBackgroundColor(Color.GREEN);
auswertung.setTextColor(Color.BLACK);
auswertung.setText("Leider falsch");
gedruckt = true;
}
}
break;
case R.id.antwortB:
if (aw ==2){
if (gedruckt==false){
antwortB.setBackgroundColor(Color.GREEN);
korrekt = korrekt +1;
auswertung.setTextColor(Color.BLACK);
gedruckt = true;
}
}else{
if (gedruckt==false){
antwortB.setBackgroundColor(Color.RED);
rButton.setBackgroundColor(Color.GREEN);
auswertung.setTextColor(Color.BLACK);
auswertung.setText("Leider falsch");
gedruckt = true;
}
}
break;
case R.id.antwortC:
if (aw ==3){
if (gedruckt==false){
antwortC.setBackgroundColor(Color.GREEN);
korrekt = korrekt +1;
auswertung.setTextColor(Color.BLACK);
gedruckt = true;
}
}else{
if (gedruckt==false){
antwortC.setBackgroundColor(Color.RED);
rButton.setBackgroundColor(Color.GREEN);
auswertung.setTextColor(Color.BLACK);
auswertung.setText("Leider falsch");
gedruckt = true;
}
}
break;
case R.id.antwortD:
if (aw ==4){
if (gedruckt==false){
antwortD.setBackgroundColor(Color.GREEN);
korrekt = korrekt +1;
auswertung.setTextColor(Color.BLACK);
gedruckt = true;
}
}else{
if (gedruckt==false){
antwortD.setBackgroundColor(Color.RED);
rButton.setBackgroundColor(Color.GREEN);
auswertung.setTextColor(Color.BLACK);
auswertung.setText("Leider falsch");
gedruckt = true;
}
}
break;
case R.id.wigger:
fragestellen();
break;
}
}
So when I run the program, I get an error which you can see here (Screenshot from my phone)
This is strange since I declared and initialized the two databases in the SAME way.

Related

Error : Cannot get a STRING value from a NUMERIC cell in Selenium

I'm trying to import data from Excel file to automate a large amount of data but I got the error "Cannot get a STRING value from a NUMERIC cell" as some of the cells has a numeric values and others has a text value.I need to extract all data and insert it as inputs for the page fields. i got the error stating from
signin_credentials[i][2] = configuration.getData(0, i, 5);
signin_credentials[i][3] = configuration.getData(0, i, 6);
Here is my code:
import org.apache.poi.ss.usermodel.CellType;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ExcelExample {
WebDriver driver;
#Test(dataProvider = "testdata")
public void demoClass(String NameEN, String NameAr, String ServiceCode, String min, String max)
throws InterruptedException {
//System.setProperty("webdriver.chrome.driver", "Path of Chrome Driver");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://192.168.1.130/Account/Login");
driver.findElement(By.name("UsernameOrEmailAddress")).sendKeys("admin");
driver.findElement(By.name("Password")).sendKeys("P#ssw0rd");
driver.findElement(By.id("LoginButton")).click();
Thread.sleep(5000);
driver.findElement(By.partialLinkText("Services")).click();
Thread.sleep(500);
//click on service list
driver.findElement(By.partialLinkText("Service List")).click();
Thread.sleep(500);
//click on rotate circle
driver.findElement(By.xpath("/html/body/section[2]/div/div[1]/div/div/div[2]/div[2]/a[4]/span/span")).click();
Thread.sleep(2000);
//click on +
driver.findElement(By.xpath("/html/body/section[2]/div/div[1]/div/div/div[2]/div[2]/a[3]/span")).click();
Thread.sleep(1000);
//write on service name
driver.findElement(By.id("Name")).sendKeys(NameEN);
Thread.sleep(500);
//write on service name Arabic
driver.findElement(By.id("NameAr")).sendKeys(NameAr);
WebElement drodown = driver.findElement(
By.xpath("//*[#id=\"ServiceCreateForm\"]/div/div/div/div[2]/div[3]/div[1]/div/div/button"));
drodown.click();
WebElement range = driver.findElement(
By.xpath("//*[#id=\"ServiceCreateForm\"]/div/div/div/div[2]/div[3]/div[1]/div/div/div/ul/li[2]/a"));
range.click();
//select min amount
driver.findElement(By.name("MinValue")).sendKeys(min);
//select max amount
driver.findElement(By.name("MaxValue")).sendKeys(max);
//driver.findElement(By.xpath("//*[#id=\"ServiceCreateForm\"]/div/div/div/div[2]/div[7]/div/button")).click();
}
#AfterMethod
void ProgramTermination() {
//driver.quit();
}
#DataProvider(name = "testdata")
public Object[][] testDataExample() {
ReadExcelFile configuration = new ReadExcelFile("C:\\Users\\Desktop\\file.xlsx");
int rows = configuration.getRowCount(0);
Object[][] signin_credentials = new Object[rows][5];
for (int i = 0; i < rows; i++) {
signin_credentials[i][0] = configuration.getData(0, i, 3);
signin_credentials[i][1] = configuration.getData(0, i, 4);
signin_credentials[i][2] = configuration.getData(0, i, 5);
signin_credentials[i][3] = configuration.getData(0, i, 6);
}
return signin_credentials;
}
}
and here is my excel class:
package Login;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFile {
XSSFWorkbook work_book;
XSSFSheet sheet;
public ReadExcelFile(String excelfilePath) {
try {
File s = new File(excelfilePath);
FileInputStream stream = new FileInputStream(s);
work_book = new XSSFWorkbook(stream);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public String getData(int sheetnumber, int row, int column) {
sheet = work_book.getSheetAt(sheetnumber);
String data = sheet.getRow(row).getCell(column).getStringCellValue();
return data;
}
public int getRowCount(int sheetIndex) {
int row = work_book.getSheetAt(sheetIndex).getLastRowNum();
row = row + 1;
return row;
}
}
try ((xssfcell) sheet.getRow(row).getCell(column)).getRawValue()
Which actually worked for me in a differnt way
You dont really need to use the multiple if conditions.
Improved method getData(int sheetnumber, int row, int column) that returns always data as a String or null:
// add this two imports
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
...
public String getData(int sheetnumber, int row, int column) {
sheet = work_book.getSheetAt(sheetnumber);
XSSFCell cell = sheet.getRow(row).getCell(column);
String data = null;
if (cell != null) {
CellType cellType = cell.getCellType();
if (cellType.toString() == "STRING") {
data = cell.getStringCellValue();
}
else if (cellType.toString() == "NUMERIC") {
data = String.valueOf(cell.getNumericCellValue());
}
else if (cellType.toString() == "FORMULA") {
data = cell.getCellFormula();
}
else if (cellType.toString() == "BOOLEAN") {
data = String.valueOf(cell.getBooleanCellValue());
}
else if (cellType.toString() == "ERROR") {
// let data be null or assign some value like this
data = "ERROR in sheet nr. " + sheetnumber + " row nr. " + row + " column nr. " + column;
}
else if (cellType.toString() == "BLANK") {
// let data be null or assign some value like this
data = "BLANK cell in sheet nr. " + sheetnumber + " row nr. " + row + " column nr. " + column;
}
else {
// let data be null or assign some value like this
data = "UNKNOWN cell type in sheet nr. " + sheetnumber + " row nr. " + row + " column nr. " + column;
}
}
return data;
}

Both vacuum_count and analyze_count are zero after VACUUM ANALYZE

I've written a unit test which modifies a table (INSERT's and DELETE's), then manually VACUUM's and ANALYZE's it, and then I query pg_stat_user_tables to make sure that VACUUM and ANALYZE did have some effect.
I use the following SQL:
select
tbl.relid,
tbl.schemaname,
tbl.n_tup_del,
tbl.n_live_tup,
tbl.n_dead_tup,
tbl.n_mod_since_analyze,
tbl.vacuum_count,
tbl.analyze_count
from
pg_stat_user_tables tbl
where
tbl.relname = lower('...')
and schemaname = current_schema();
for regular tables and
select
tbl.relid,
tbl.schemaname,
tbl.n_tup_del,
tbl.n_live_tup,
tbl.n_dead_tup,
tbl.n_mod_since_analyze,
tbl.vacuum_count,
tbl.analyze_count
from
pg_stat_user_tables tbl
join
pg_namespace nsp
on
tbl.schemaname = nsp.nspname
where
tbl.relname = lower('...')
and nsp.oid = pg_my_temp_schema();
for temporary ones.
Still, when I run my example, I observe that both vacuum_count and analyze_count are zero, and the table contains lots of dead tuples, e.g.:
relid = 913896
schemaname = pg_temp_20
n_tup_del = 10000
n_live_tup = 10000
n_dead_tup = 10000
n_mod_since_analyze = 30000
vacuum_count = 0
analyze_count = 0
Why's that?
The self-contained code sample is below:
package com.example;
import static com.example.AutoCommitMode.COMMIT;
import static com.example.AutoCommitMode.ON;
import static com.example.AutoCommitMode.ROLLBACK;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.postgresql.ds.PGSimpleDataSource;
import org.postgresql.ds.common.BaseDataSource;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public final class PostgreSqlVacuumTest {
private static final String JDBC_URL = "jdbc:postgresql://localhost:5432/postgres?currentSchema=sandbox";
#DataProvider
private static #Nullable Object #NonNull[]#NonNull[] getParameters() {
#NonNull final List<#Nullable Object #NonNull[]> parameters = new ArrayList<>();
parameters.add(new #Nullable Object[] {"A", false, ON});
parameters.add(new #Nullable Object[] {"B", false, COMMIT});
parameters.add(new #Nullable Object[] {"C", false, ROLLBACK});
parameters.add(new #Nullable Object[] {"D", true, ON});
parameters.add(new #Nullable Object[] {"E", true, COMMIT});
parameters.add(new #Nullable Object[] {"F", true, ROLLBACK});
return parameters.toArray(new #Nullable Object #NonNull[0]#NonNull[]);
}
#Test(dataProvider = "getParameters")
#SuppressWarnings({"static-method", "incomplete-switch"})
public void test(#NonNull final String tableName,
final boolean temporary,
final AutoCommitMode mode)
throws SQLException {
final DataSource dataSource = new PGSimpleDataSource();
((BaseDataSource) dataSource).setUrl(JDBC_URL);
try (final Connection conn = dataSource.getConnection("user", "password")) {
try (final Statement stmt = conn.createStatement()) {
try {
stmt.executeUpdate(format("drop table %s", tableName));
} catch (#SuppressWarnings("unused") final SQLException ignored) {
// ignore
}
stmt.executeUpdate(format("create %stable %s (id bigint not null)",
temporary ? "temporary " : "",
tableName));
conn.setAutoCommit(mode.autoCommit);
for (int i = 0; i < 10000; i++) {
stmt.executeUpdate(format("insert into %s (id) values (%d)", tableName, i));
}
stmt.executeUpdate(format("delete from %s", tableName));
for (int i = 0; i < 10000; i++) {
stmt.executeUpdate(format("insert into %s (id) values (%d)", tableName, i));
}
switch (mode) {
case COMMIT:
conn.commit();
break;
case ROLLBACK:
conn.rollback();
break;
}
try (final ResultSet countHolder = stmt.executeQuery(format("select count(*) from %s", tableName))) {
Assert.assertTrue(countHolder.next());
final long count = countHolder.getLong(1);
Assert.assertEquals(count, mode == ROLLBACK ? 0L : 10000L);
Assert.assertFalse(countHolder.next());
}
switch (mode) {
case ON:
stmt.executeUpdate(format("vacuum analyze %s", tableName));
break;
case COMMIT:
case ROLLBACK:
// VACUUM cannot be executed inside a transaction block.
conn.setAutoCommit(true);
try {
stmt.executeUpdate(format("vacuum analyze %s", tableName));
} finally {
conn.setAutoCommit(false);
}
break;
}
diagnose(tableName, temporary, stmt);
}
}
}
private static void diagnose(#NonNull final String tableName,
final boolean temporary,
#NonNull final Statement stmt)
throws SQLException {
final List<String> columns = asList("relid", "schemaname", "n_tup_del", "n_live_tup", "n_dead_tup", "n_mod_since_analyze", "vacuum_count", "analyze_count");
final String diagSql = temporary
? "select\n" +
" tbl.relid,\n" +
" tbl.schemaname,\n" +
" tbl.n_tup_del,\n" +
" tbl.n_live_tup,\n" +
" tbl.n_dead_tup,\n" +
" tbl.n_mod_since_analyze,\n" +
" tbl.vacuum_count,\n" +
" tbl.analyze_count\n" +
"from\n" +
" pg_stat_user_tables tbl\n" +
"join\n" +
" pg_namespace nsp\n" +
"on\n" +
" tbl.schemaname = nsp.nspname\n" +
"where\n" +
" tbl.relname = lower('%s')\n" +
" and nsp.oid = pg_my_temp_schema()"
: "select\n" +
" tbl.relid,\n" +
" tbl.schemaname,\n" +
" tbl.n_tup_del,\n" +
" tbl.n_live_tup,\n" +
" tbl.n_dead_tup,\n" +
" tbl.n_mod_since_analyze,\n" +
" tbl.vacuum_count,\n" +
" tbl.analyze_count\n" +
"from\n" +
" pg_stat_user_tables tbl\n" +
"where\n" +
" tbl.relname = lower('%s')\n" +
" and schemaname = current_schema()";
try (final ResultSet rset = stmt.executeQuery(format(diagSql, tableName))) {
while (rset.next()) {
System.out.println("---------------");
for (final String column : columns) {
System.out.println("\t" + column + " = " + rset.getObject(column));
}
}
}
}
}
enum AutoCommitMode {
ON(true),
COMMIT(false),
ROLLBACK(false),
;
final boolean autoCommit;
AutoCommitMode(final boolean autoCommit) {
this.autoCommit = autoCommit;
}
}
VACUUM (without FULL) marks dead tuples as ready for reuse, it’s also able to trumcate dead tuples at the end of the table, but it doesn’t eliminate those dead tuples.
VACUUM FULL rewrites the whole table from scratch so dead tuplesgwt removed in the process, but it requires an exclusive lock on the table:
https://www.postgresql.org/message-id/dcc563d10710021855l7ac247ebv62c5fc44a321ee1f%40mail.gmail.com
If you have a large table and would like to run VACUUM FULL on it while being able to use it in the process, consider using https://github.com/reorg/pg_repack/.
Are you sure the user (the one you use to manually run the VACUUM) has the sufficient privileges ?
The doc says:
"VACUUM processes every table in the current database that the current user has permission to vacuum"

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();
...
}

If + try - catch in method not working properly

I'm working on an SQLite based app. Everything is working fine, except my if-else statements in my method. The saving and stuff works, just the checking is giving me a pretty high blood pressure. I'm hoping one of you is much smarter than i am and finds the probably obvious mistake i made:
public void save() {
// get length of EditText
int dateLength, mileageLength, amountLength, lpriceLength, tpriceLength;
dateLength = date_widget.getText().length();
mileageLength = mileage_widget.getText().length();
amountLength = amount_widget.getText().length();
lpriceLength = price_widget.getText().length();
tpriceLength = totalPrice_widget.getText().length();
// Start save method if EditTexts are not empty.
if (dateLength > 0 || mileageLength > 0 || amountLength > 0
|| lpriceLength > 0 || tpriceLength > 0) {
// Get the value of each EditText and write it into the
// String/doubles
String date = date_widget.getText().toString();
double mileage = Double
.valueOf(mileage_widget.getText().toString());
double amount = Double.valueOf(amount_widget.getText().toString());
double lprice = Double.valueOf(price_widget.getText().toString());
double tprice = Double.valueOf(totalPrice_widget.getText()
.toString());
// Check if mileage is increasing, else cancel and show toast
int checkMileage = Integer.parseInt(db
.getSearchResult("mileage", 0));
if (checkMileage < mileage) {
try {
// if (id == null) {
db.insert(date, mileage, amount, lprice, tprice);
Toast.makeText(this, R.string.action_input_saved,
Toast.LENGTH_SHORT).show();
finish();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "ERROR " + e, Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(
this,
"Your current mileage must be more than the last saved mileage",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "finish your input", Toast.LENGTH_LONG).show();
}
}
My Method in the DbAdapter class:
public String getSearchResult(String sql, int cmd) {
if (cmd == 0) {
String countQuery = "SELECT " + sql + " FROM " + TABLE_NAME
+ " WHERE _id = (SELECT max(_id) FROM " + TABLE_NAME + ")";
Cursor cursor = db.rawQuery(countQuery, null);
cursor.moveToFirst();
String tmp = cursor.getString(0);
cursor.close();
// return count
return tmp;
} else if (cmd == 1) {
int sum = 0;
String countQuery = "SELECT " + sql + " FROM " + TABLE_NAME;
String idQuery = "SELECT _id FROM " + TABLE_NAME
+ " WHERE _id = (SELECT max(_id) FROM " + TABLE_NAME + ")";
Cursor cursor = db.rawQuery(countQuery, null);
Cursor id = db.rawQuery(idQuery, null);
// berechnung
cursor.moveToFirst();
id.moveToFirst();
int maxId = Integer.parseInt(id.getString(0));
for (int i = 0; i < maxId; i++) {
int tmp = Integer.parseInt(cursor.getString(0));
sum = sum + tmp;
cursor.moveToNext();
}
cursor.close();
id.close();
return String.valueOf(sum);
} else if (cmd == 2 && sql == "mileage") {
int sum = 0;
String countQuery = "SELECT " + sql + " FROM " + TABLE_NAME;
String idQuery = "SELECT _id FROM " + TABLE_NAME
+ " WHERE _id = (SELECT max(_id) FROM " + TABLE_NAME + ")";
Cursor cursor = db.rawQuery(countQuery, null);
Cursor id = db.rawQuery(idQuery, null);
// berechnung
cursor.moveToFirst();
id.moveToFirst();
int maxId = Integer.parseInt(id.getString(0));
if (maxId > 1) {
int array[] = new int[maxId];
// Array füllen
for (int i = 0; i < maxId; i++) {
array[i] = Integer.parseInt(cursor.getString(0));
// sum = sum + tmp;
cursor.moveToNext();
}
for (int k = 1; k < maxId; k++) {
int tmp;
tmp = array[k] - array[k - 1];
sum = sum + tmp;
}
cursor.close();
id.close();
return String.valueOf(sum);
} else {
return "--";
}
}
return "Wrong CMD";
}
I is pretty messy, i know
Turning comment into an answer:
Switch all || to && in your first if. Otherwise you will try to process everything even if only one field is filled in.

Not reading a file?

So I want to read a text file but for some strange reason it can't find the file. I have used these methods before, and I therefore have no idea why this isn't working can someone please help me out?
EDIT:
sorry guys I left out a big piece of info which is that it can find the file when it is writing to it but not when it is reading from it. Thanks for all your guys' help and sorry for wasting your time asking a question I didn't need the answer to... Again sorry.
Some more info:
"Assets.txt" is in both the project's root folder as well as in the src/assetregistry
"Assets.txt" will be there when the program is run
All I get is the JOption messege from the catch exception in the readFromFile() method
According to the properties of assetRegistry the working directory is
"C:\Users\Justin\Documents\NetBeansProjects\assetregistry\src\assetregistry"
Thank you to everyone who helped, especially Chris and Andrew Thompson. The program now work and the following is the updated version. Feel free to copy it if you want. It's really a simple program.
Main class:
package assetregistry;
import java.io.IOException;
import javax.swing.JOptionPane;
public class Assetregistry {
public static void main(String[] args) throws IOException {
new Assetregistry();
}
assetArray aa = new assetArray();
public Assetregistry() throws IOException {
aa.readFromFile ();
char choice = 'Z';
while (choice != 'X') {
choice = menu();
options(choice);
}
}
public char menu() {
char ch = JOptionPane.showInputDialog("\t" + "Welcome to asset registry. Please input your choice" + "\n" + "A: Enter new asset" + "\n" + "B: Calculate depreciation and display" + "\n" + "X: Exit").toUpperCase().charAt(0);
return ch;
}
private void options(char c) throws IOException {
switch (c) {
case 'A':
aa.enterAsset();
break;
case 'B':
aa.calculate();
break;
case 'X':
System.exit(0);
break;
}
}
}
Array/method class
package assetregistry;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
public class assetArray {
asset[] aArr = new asset[100];
private double year;
private double month;
private int count = 0;
Assetregistry AR;
String home = System.getProperty("user.home");
File userHome = new File(home);
File file = new File(userHome,"Assets.txt");
public assetArray() throws IOException {
}
public void enterAsset() throws IOException {
int choice = JOptionPane.YES_OPTION;
while (choice == JOptionPane.YES_OPTION) {
String name = JOptionPane.showInputDialog("Enter asset name");
double costP = Double.parseDouble(JOptionPane.showInputDialog("Enter the cost price of the asset"));
int lSpan = Integer.parseInt(JOptionPane.showInputDialog("Enter the amount of years you wish to keep the asset"));
double mBought = Double.parseDouble(JOptionPane.showInputDialog("Enter the month the asset was bought (As a number)"));
double yBought = Double.parseDouble(JOptionPane.showInputDialog("Enter the year the asset was bought"));
double depr = (1.00 / lSpan * 100.00);
aArr[count] = new asset(name, costP, lSpan, yBought, mBought, depr);
PrintWriter pw = new PrintWriter(new FileWriter(file, true));
pw.println(aArr[count].toString());
pw.close();
count++;
choice = JOptionPane.showConfirmDialog(null, " Do you want to enter another asset?", " Enter another asset?", JOptionPane.YES_NO_OPTION);
}
}
public void calculate() {
String name;
int lSpan;
double ybought;
double mbought;
double pValue;
double Rate;
double deprExp;
double numYears;
double fValue;
double accDepr;
String[] mnth = new String[12];
mnth[0] = "January";
mnth[1] = "February";
mnth[2] = "March";
mnth[3] = "April";
mnth[4] = "May";
mnth[5] = "June";
mnth[6] = "July";
mnth[7] = "August";
mnth[8] = "September";
mnth[9] = "October";
mnth[10] = "November";
mnth[11] = "December";
if (count > 0) {
year = Integer.parseInt(JOptionPane.showInputDialog("Enter the year you wish to calculate depreciation for"));
month = Integer.parseInt(JOptionPane.showInputDialog("Enter the month you wish to calculate depreciation for"));
int m = (int) month;
int y = (int) year;
System.out.println("Asset regestry" + "\t" + mnth[m-1] + " " + y);
for (int i = 0; i < count; i++) {
name = aArr[i].getName();
lSpan = aArr[i].getLifeSpan();
ybought = aArr[i].getyBought();
mbought = aArr[i].getmBought();
pValue = aArr[i].getCostP();
Rate = aArr[i].getDeprR();
int m2 = (int) mbought;
int y2 = (int) ybought;
deprExp = pValue - (pValue * ((1.00 - ((Rate))) * 1.00 / 100.00));
numYears = (year + (month / 12.00)) - (ybought + mbought / 12.00);
fValue = pValue * (1.00 - (((Rate) * (numYears)) / 100.00));
if (fValue <= 0.00) {
fValue = (int) 1;
}
accDepr = pValue - fValue;
System.out.println("\n" + "Asset: " + name);
System.out.println("Life span: " + lSpan + "yrs");
System.out.println("Cost price: " + "R" + pValue);
System.out.println("Date acquired: " + mnth[m2-1] + " " + y2);
System.out.println("Depreciatin rate (p.a.): " + Rate + "%");
System.out.println("Depreciation(p.a.): R" + deprExp);
System.out.println("Accumulated depreciation: R" + accDepr);
System.out.println("Current book value: R" + fValue);
System.out.println("_________________________________________");
}
} else {
JOptionPane.showMessageDialog(null, "There are no assets in memory", "NO ASSETS!", JOptionPane.ERROR_MESSAGE);
}
}
/**
*
*/
public void readFromFile() {
String line = "";
try {
BufferedReader fr = new BufferedReader(new FileReader(file));
line = fr.readLine();
while (line != null) {
StringTokenizer stk = new StringTokenizer(line, "#");
String name = stk.nextToken();
double costP = Double.parseDouble(stk.nextToken());
int lSpan = Integer.parseInt(stk.nextToken());
double yBought = Double.parseDouble(stk.nextToken());
double mBought = Double.parseDouble(stk.nextToken());
double deprR = Double.parseDouble(stk.nextToken());
aArr[count] = new asset(name, costP, lSpan, yBought, mBought, deprR);
count++;
line = fr.readLine();
}
fr.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "There is a file missing.", "FILE MISSING!", JOptionPane.ERROR_MESSAGE);
}
}
}
Assets class
package assetregistry;
/**
*
* #author Justin
*/
public class asset {
private String name;
private double costP;
private int lifeSpan;
private double yBought;
private double mBought;
private double deprR;
public asset(){
}
public asset(String name, double costP, int lifeSpan, double yBought, double mBought, double deprR) {
this.name = name;
this.costP = costP;
this.lifeSpan = lifeSpan;
this.yBought = yBought;
this.mBought = mBought;
this.deprR = deprR;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getCostP() {
return costP;
}
public void setCostP(double costP) {
this.costP = costP;
}
public int getLifeSpan() {
return lifeSpan;
}
public void setLifeSpan(int lifeSpan) {
this.lifeSpan = lifeSpan;
}
public double getyBought() {
return yBought;
}
public void setyBought(double yBought) {
this.yBought = yBought;
}
public double getmBought() {
return mBought;
}
public void setmBought(double mBought) {
this.mBought = mBought;
}
public double getDeprR() {
return deprR;
}
public void setDeprR(double deprR) {
this.deprR = deprR;
}
#Override
public String toString ()
{
String stg = "";
stg += name + "#" + costP + "#" + lifeSpan + "#" + yBought + "#" + mBought + "#" + deprR + "#";
return stg;
}
}
String home = System.getProperty("user.home");
System.out.println("User home directory is: " + home);
File userHome = new File(home);
// Put files in a known and reproducible path!
File file = new File(userHome, "Assets.txt");
It depends where you have put "Assets.txt" in your file system. If you are running the code from inside netbeans, then the line:
File file = new File("Assets.txt");
will be looking for the file in the root folder of your project e.g. */NetBeansProjects/INSERT_PROJECT_NAME/ (if you're not then it will be looking for the file in the same directory the application is running in).I noticed you have the line:
URL url = AR.getClass().getResource("/Assets.txt");
but you never use url in your code. Are you trying to look for the file in the same directory as your "Assetregistry" class and forgot to use url to specify the location? If this is the case then remove the "/" from the beginning of the name and construct the file like this:
URL url = Assetregistry.class.getResource("Assets.txt");
File file = new File(url.toURI());
Hope this helps :)

Categories

Resources