Properties of object null even after setting - java

I have been looking at this for a while. First off, here is some code:
MyActivity.java:
MeasurementType type = handler.getMeasurementType(DEFAULT_TYPE);
ArrayList<Unit> unitsConverted = new ArrayList<Unit>();
unitsConverted.addAll(Arrays.asList(type.getUnits()));
DataBaseHandler.java:
public MeasurementType getMeasurementType(String measurementType) {
SQLiteDatabase db = this.getReadableDatabase();
int num = getMeasurementUnitCount(measurementType);
MeasurementType mType = MeasurementType.getMeasurementType(measurementType);
Unit[] units = new Unit[num];
String getUnits = "SELECT unit_name, view FROM " + measurementType;
Cursor cursor = db.rawQuery(getUnits, null);
for(int i = 0; i <= units.length-1; i++) {
if(cursor.moveToNext()) {
Unit u = new Unit();
u.setUnitName(cursor.getString(0));
u.setView(cursor.getInt(1));
units[i] = u;
}
}
mType.setUnits(units);
return mType;
}
I am not quite sure why this is happening but after this line:
mType.setUnits(units)
The debugger is telling me that the property is null...
num is 21 which is right, the array units goes from 0 to 20, which is right.
Here is my implementation of the setUnits(units) method in my MeasurementType class:
protected void setUnits(Unit[] passedUnits) {
units = new Unit[passedUnits.length+1];
System.arraycopy(passedUnits, 0, units, 0, passedUnits.length);
}
it works ok too...
in fact when the method getMeasurement is finished and I am back in my activity, it still says null.
However stepping through to creating the ArrayList and then doing:
unitsConverted.addAll(Arrays.asList(type.getUnits()));
works fine...the ArrayList is populated fine. But one thing that I don't understand is why the debugger is telling me that the property is null...it has been happening to this specific circumstance for some time now, I haven't been able to fix it.
Further information you might need to know is that MeasurementType is an abstract class that instantiates a subclass based on a string that is passed to it, so it definitely creates a subclass and intialises everything :)

Related

What does the following code analysis mean?

I have an object instantiated like the following in only one place in my code(AggregateFunctions).
private String selectColumns() {
String query = "SELECT ";
if (this.distinctResults) {
query = query + "DISTINCT ";
}
SelectColumn selectColumn = new SelectColumn(this);
if (!this.applyAggregation) {
for (Object object : this.columns) {
query = selectColumn.selectColumn(query, object);
}
} else {
AggregateFunctions aggregateFunctions = new AggregateFunctions(this);
query = query + aggregateFunctions.select();
}
//Remove extra ', '
query = query.substring(0, query.length() - 2) + " FROM ";
return query;
}
The constructors:
public AggregateFunctions(#NotNull SqlQueryGenerator sqlQueryGenerator) {
this.spaceEncloser = sqlQueryGenerator.getSpaceEncloser();
this.selectColumn = new SelectColumn(sqlQueryGenerator);
JSONObject formData = sqlQueryGenerator.getFormData();
this.columns = formData.getJSONArray("columns");
this.aggregateJson = formData.getJSONObject("functions").getJSONArray("aggregate");
this.aggregatesList = new ArrayList<Aggregate>();
prepareAggregates();
this.query = new StringBuilder();
}
public SelectColumn(SqlQueryGenerator sqlQueryGenerator) {
this.sqlQueryGenerator = sqlQueryGenerator;
}
But IntelliJ Code Analysis says the following about recursive calls. Basically I didn't understand the meaning. Can anyone elaborate to help me understand?
Problem synopsis
Constructor has usage(s) but they all belong to recursive calls chain that has no members reachable from entry points.   
Problem resolution
Safe delete
Comment out
Add as Entry Point
This is a warning from the Unused declaration inspection. IntelliJ IDEA thinks the constructor is not reachable from any entry points. The constructor is not unused however, but the usages are themselves unreachable.
If this is not the case for your code, it may be a bug in IntelliJ IDEA.
Probably in the constructor of AggregateFunctions in the code that you call you go back to the method selectColumns() in the other class. This way a recurrsion is never going to end.
My guess is that either here
JSONObject formData = sqlQueryGenerator.getFormData();
Or somewhere in here:
this.selectColumn = new SelectColumn(sqlQueryGenerator);
You go to the previous class and to the same method that creates a new aggreggate and a loop is happening.
You call the AggregateFunction with this - which is the same object. But then in the constructor you call methods of this. Check these methods and if any of them has another creation of AggregateFunction object - there is your problem.
I had this issue and it was because the object was not used anywhere else

Java - Method on new operator

Well, I'm not sure if I can do this but let me ask the question anyway...
I got class Budynek which constructor is like this:
public Budynek(int numerBudynku)
{
this.id.nrBudynku = numerBudynku;
this.id.nrPietra = 0;
this.id.nrPokoju = 0;
}
so I am creating it like this:
Budynek Budynek1 = new Budynek(1);
Budynek Budynek2 = new Budynek(2);
Now I want to ask if there is any way to create a method that create new Budynek for me? Lets say if I use switch case, and case 1 will be "create new Budynek"
then I would like this method to do something like this
e.g licznik = 1
Budynek Budynek+licznik(so it will be Budynek1) = new Budynek(licznik)
then just licznik = licznik + 1;
is that possible?
You can create a List and store everything there, since your are indexing anyways with budynek+index
List<Budynek> budynekList = new ArrayList<Budynek>();
budynekList.add(new Budynek(10));
budynekList.add(new Budynek(20));
budynekList.add(new Budynek(400));
budynekList.get(index); // now you have your budynek objects with the given index.
As in the comments already pointed out, you can't declare variables on runtime.
Either
enum Budynek {
BUDYNEK_A,
BUDYNEK_B,
BUDYNEK_C;
public ID id;
private Budynek() {
this.id.nrBudynku = 1 + ordinal();
this.id.nrPietra = 0;
this.id.nrPokoju = 0;
}
}
Budynek.BUDY_A.id.nrBudynku
or you must go for an array:
Budynek[] budyneki = new Budynek[3];
...
budyneki[0].id.nrBudynku
budyneki[1].id.nrBudynku
budyneki[2].id.nrBudynku

How do I print my an array in a toString() method?

I'm trying to print an array via toString() so I can call it to another method. What exactly am I doing wrong? Why isn't it compiling and what is a better solution.
public class Applicants
{
private String applicant[];
public Applicants()
{
Application student1 = new Application()
Application student2 = new Application()
Application student3 = new Application()
Application student4 = new Application()
Application student5 = new Application()
Application student6 = new Application();
Application applicant[] = new Application[5];
applicant[0] = student1;
applicant[1] = student2;
applicant[2] = student3;
applicant[3] = student4;
applicant[4] = student5;
applicant[5] = student6;
for (int index = 0; index < applicant.length; index++)
{
System.out.println(applicant[index]);
}
}
public String toString(String[] applicant)
{
String output = new String();
String total;
for (int index = 0; index < applicant.length; index++)
{
total = System.out.println(applicant[index]);
}
return total;
}
}
There are three things wrong, and one "hey, pay attention".
You are shadowing your field applicant inside of your constructor. What this means is when you're done with your constructor, your String[] is null. Not full of null, just null.
What you probably meant to do was declare private Application[] applicant as your field, then not redeclare it inside of your constructor.
total = System.out.println(applicant[index]); is not a valid statement. You cannot assign the result of a void method to anything. You have it right in your constructor, so it's surprising that you didn't get it correct down here.
toString does not take any arguments. Use your field.
Please have toString defined on your Application object, as that will make your life easier. Otherwise, extract meaningful information from that object. You're going to do some string concatenation on this one in either event, which I leave as an exercise for the reader.
You need to declare the toString method in the Application class:
public class Application {
#Override
public String toString() {
// your code here
}
}
Note the use of the Override annotation. This will make the compiler check that you are actually overriding the method you say you are - in your current code, you are not as toString does not take any parameters.
As for implementation of toString, I would go with Google Guava
#Override
public String toString() {
return MoreObjects.toStringHelper(this.getClass()).add(..).add(..).toString();
}
See here for more info: https://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained
Guava docs

Java: Copy Constructor not going as planned

I have a bit of a problem. I'm making a Finite Automata checker.
Given an input, and the DFA, does it end on a accepting state.
My problem is creating a new DFA_State from another's target.
DFA_State state0, state1, curr_state, init_state, temp; //fine, I think
state0 = new DFA_State();
state1 = new DFA_State();
state0 = new DFA_State("State 0",true, state0, state1); //fine, I think
init_state = new DFA_State(state0); //fine, I think
but, this bit is throwing up problems.
temp = new DFA_State(curr_state.nextState(arr1[i]));
*
*
curr_state = new DFA_State(temp);
Thanks for any help,
Dave
Edit:
God I was retarded when I did this, AFAIK, I just wasn't thinking straight, added methods to set the values to the DFA_State object.
//in DFA_State class
public void set(DFA_State on_0, DFA_State on_1, Boolean is_accepting, String name){
this.on_0 = on_0;
this.on_1 = on_1;
this.is_accepting = is_accepting;
this.name = name;
}
//in main
DFA_State state0, state1, curr_state;
state0 = new DFA_State();
state1 = new DFA_State();
state0.set(state0, state1, false, "State 0");
state1.set(state1, state0, true, "State 1");
curr_state = state0;//initial state
//iterate across string input changing curr_state depending on char c
curr_state = getNextState(c);
//at end
if(curr_state.isAccepting())
System.out.println("Valid, " + curr_state.getName() + " is accepting);
else
System.out.println("Invalid, " + curr_state.getName() + " is not accepting);
In that first line, you declare the variables state0, state1, curr_state, init_state and temp as being variables of type DFA_State. However, that only declares them, they are not yet initialized. The next few lines are all okay. Second line creates a state without anything in it and assigns it to state0, so does the third line for state1. Fourth line overwrites your previous state0 assignment with a new DFA_State that has actual contents. Fifth line creates a DFA_State as a copy of state0 and assigns it to init_state.
Assuming there's nothing in between this and the first line of your second code block, now you'll get a problem. You're assigning temp with a new DFA_State that uses a copy-constructor with an argument relying on curr_state. But at that point, that variable hasn't been initialized yet. Just because it was declared doesn't mean it has somehow already been structured in memory. When you call nextState on it, there's simply no variable to resolve this to. Don't expect to get something like a pointer that will eventually point to a part of what you put in curr_state.
I'm just guessing, but from your code style I'd say you have a background in C or C++. Look into the differences between those languages and Java. If possible, I'd also advise you to make your DFA_State class immutable, since this is more reliable and will avoid mistakes. That means getting rid of the no-args constructor. Here's a reworking of it (not actually compiled, might contain errors):
package foundations.of.computing;
/**
*
* #author Kayotic
*/
class DFA_State {
private final String state;
private final DFA_State on_0;
private final DFA_State on_1;
private final boolean isAccepting;
//private DFA_State dummy;
public DFA_State(DFA_State arg) {
//this(arg.is_accepting(), arg.on0(), arg.on1());
state = arg.get_name();
isAccepting = arg.is_accepting();
on_0 = arg.on0();
on_1 = arg.on1();
}
public DFA_State(String name, Boolean accepting, DFA_State on0, DFA_State on1) {
state = name;
isAccepting = accepting;
on_0 = on0;
on_1 = on1;
}
public String get_name(){
return state;
}
public Boolean is_accepting() {
return isAccepting;
}
public DFA_State on0() {
return on_0;
}
public DFA_State on1() {
return on_1;
}
public DFA_State nextState(char i) {
if (i == '0') {
return on0();
} else if (i == '1') {
return on1();
} else {
System.out.println("Error with input");
return null;
}
}
}
Even if you can't make the instance variables final, it's best to at least make them private, since you already have methods for getting them.
There are better memory representations of DFAs than the object-oriented.
You should use a simple lookuptable:
int[] table = new int[vocabularyCount][stateCount];
Every State and every word gets a number, starting with 0.
Fill the table with the state transitions, or -1, if there is no transition. Now you just need the translation methods for the states and the words.
Heres a generic DFA algorithm:
public boolean checkSentence(String s, int[] finishes) {
// fill table
int state = 0; // assuming S0 is the start state
for (int i = 0; i < s.length(); i++) {
state = table[translate(s.charAt(i))][s];
}
for (int i = 0; i < finishes.length; i++) {
if (finishes[i] == state) {
return true;
}
}
return false;
}
The program is quite poorly written. Look at this in your FoundationsOfComputing.java:
state0 = new DFA_State();
state1 = new DFA_State();
state0 = new DFA_State("State 0",true, state0, state1);
You essentially created 3 instances of state - two instances which are not initialized (first two lines in your code) - all their instance variables are null.
Then you create the third instance, which you point to the first two uninitialized ones, and assign it to state0 variable. Please note, at this point, it is only the value of the variable that changes, not the values you passed in the DFA-State constructor!!! So, what you now have in state0 is a state that points to two uninitialized states.
Now let's look at the code further down in the FoundationsOfComputing.java:
while (i < arr1.length) {//loops through array
System.out.println(i + ". scan shows " + arr1[i]);
temp = new DFA_State(curr_state.nextState(arr1[i]));
System.out.println(" "+curr_state.get_name()+ " moves onto " + temp.get_name());
curr_state = new DFA_State(temp);
i++;
}
I am guessing this throws NullPointerException - that code moves to the on_0 state of state0 - which is a state that has not been initialized (all it's instance variables are null), so in the following pass of the loop, when it calls curr_state.nextState(whatever), it would return null and you are trying to pass that to the copy-constructor which would result in NPE.
Ok so we know this is homework. Let's do this instead of telling you the answer let's try and work through it on your own. If you are seeing a NullPointerException (NPE). Grab the second line of the exception:
java.lang.NullPointerException: null
at com.blah.blah.SomeObject.someMethod(SomeArgumentType):1234 <<< here
....
That 1234 is the line number in the file that contains SomeObject. If you goto that line number you can see exactly where the NPE is being generated from. For example if line 1234 was:
this.foo = bar.indexOf("caramel");
You can easily deduce what was null. No clue? Well this can never be null so this.foo isn't the problem. If this could be null you couldn't be inside that method because this points to the instance you are currently within. Therefore, the only other statement where a variable is being dereferenced is bar so bar must be null. Let's look at your code:
temp = new DFA_State(curr_state.nextState(arr1[i]));
Say you find out the line above is tossing an exception. Well there could be several things that could be null. curr_state could be null, or arr1 could be null in which case this line would blow up. However, if arr1[i] is null or curr_state.nextState() is returning null then you won't see the NPE pointing at this line, but would be coming out of the constructor should someone try to call methods on that method parameter.
Hopefully, this will give you the tools you need to track down problems in your application by understanding exception stack traces.

How many dimensions in an array with no value

I'm a little lost (still working with Ron Jeffries's book). Here's a simple class:
public class Model{
private String[] lines;
public void myMethod(){
String[] newLines = new String[lines.length + 2];
for (i = 0, i <= lines.length, i++) {
newLines[i] = lines[i];
}
}
}
I have another class that initializes Model, and an empty array, by setting myModel = new String[0]. When I invoke myModel.myMethod(), I get a subscript out of range error. Looking at the debugger, what I see is that myModel.lines has zero dimensions and zero length. Shouldn't it have a dimension and length of 1? Granted the value of lines[0] is null, but the array itself shouldn't be, should it?
Any thoughts truly appreciated.
Randy
I think your example is probably not the same as your actual code based on your description. I think the problem is that arrays are zero-based and thus an array initialized as:
string[] lines = new string[0];
has no elements.
You need to change your loop so that you check that the index is strictly less than the length of the array. As others have indicated you also need to make sure that the array itself is not null before trying to reference it.
My take on your code:
public class Model{
private String[] lines = new string[0];
public Model( string[] lines ) {
this.lines = lines;
}
public void myMethod(){
int len = 2;
if (lines != null) {
len = len + lines.length;
}
String[] newLines = new String[len];
for (i = 0, i < lines.length, i++) {
newLines[i] = lines[i];
}
}
}
lines will be null, so lines.length will throw an exception.
I believe your other class initializing "Model" won't help since Lines itself is private. In fact, whatever you are doing to Model is probably illegal in at least 30 states.
lines is initalized to null, check for null or initialize it in this way :
private String[] lines = new String[0];
You cannot initialize an instance of Model by setting it equal to a String array. I'm actually surprised that the compiler will let you even try.
If you really want Model to be initializable with an external array, you should make a Constructor for the Model class that will take as an argument the array. Then in the body of your constructor, set the value of lines to that value.
Example:
public class Model {
private String []lines;
public Model(String [] inLines)
{
lines = inLines;
}
}
Usage:
myStringArray = new String[0];
myModel = new Model(myStringArray);
Take a look at my answer here - I think this will get you the background you are looking for on the differences between array initialization in Java and C/C++.

Categories