I have a string variable
static String[] genrename;
I am assigning values to it in one of my method and then displaying its content. It does store the value fine. But when I am accessing the String variables directly or from a getter method(). It shows a null value in the string.
Any ideas?
public class GenreParsing {
static int entries;
static String[] genrecode;
static String[] genrename;
public GenreParsing() {
}
public void parsing(String returnContent) {
try {
JSONObject jo_genres = new JSONObject(returnContent);
System.out.println(jo_genres);
JSONArray ja_genres = jo_genres.getJSONArray("genres");
System.out.println(ja_genres);
entries=ja_genres.length();
for (int i = 1; i < entries; i++) {
JSONObject jo_genre = (JSONObject) ja_genres.get(i);
JSONArray ja_genre = jo_genre.getJSONArray("genre");
JSONObject genreinfo = (JSONObject) ja_genre.get(0);
genrecode = new String[entries];
genrename = new String[entries];
genrecode[i] = genreinfo.getString("code");
genrename[i] = genreinfo.getString("name");
System.out.println(genrecode[i]);
System.out.println(genrename[i]);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
public int no_of_entries() {
System.out.println(entries);
return entries;
}
public String getgenrecode(int x) {
System.out.print(genrecode[x]);
return genrecode[x];
}
public String getgenrename(int y) {
return genrename[y];
}
}
Why are you doing genrecode=new String[entries];
and genrename=new String[entries];
inside the loop? This creates a new string array every single time through the loop, invalidating the previous assignments.
Try this instead:
genrecode=new String[entries];
genrename=new String[entries];
for(int i = 0; i < entries; i++) {
JSONObject jo_genre = (JSONObject) ja_genres.get(i);
JSONArray ja_genre=jo_genre.getJSONArray("genre");
JSONObject genreinfo = (JSONObject) ja_genre.get(0);
genrecode[i]= genreinfo.getString("code");
genrename[i] = genreinfo.getString("name");
System.out.println(genrecode[i]);
System.out.println(genrename[i]);
}
It creates a big-enough array up front and populates all the array elements. I've also changed the starting value for i
in the above code because array indexes usually start at zero, not one. You may want to check that.
One final thing to watch out for is those statics. If your class is ever allocated as multiple instances, they may overwrite each other's data in that case (especially in a threaded program where you can't dictate sequencing easily). Making these private to an instance will prevent this.
Again, it depends on how you're using the class. If it's a singleton, it won't matter (yet), but I tend to plan ahead - you don't know when you may want to change it to a non-singleton and you lose nothing (in my opinion) using instance variables even for a singleton.