Bukkit NullPointerException onEnable() - nullpointerexception

I've been working on a new plugin, and when I load it up, it gives me a "NullPointerException" error, and I can't seem to find where it could find an error. Here is the error:
[20:15:45] [Server thread/INFO]: [EntityManager] Enabling EntityManager v3.0.0.4
[20:15:45] [Server thread/INFO]: [0;31;1mEntityManager [0;32;1m3.0.0.4[0;36;1m Enabled![m
[20:15:45] [Server thread/ERROR]: Error occurred while enabling EntityManager v3.0.0.4 (Is it up to date?)
java.lang.NullPointerException
at me.AngryCupcake274.EntityManager.EntityManager.loadConfiguration(EntityManager.java:296) ~[?:?]
at me.AngryCupcake274.EntityManager.EntityManager.onEnable(EntityManager.java:63) ~[?:?]
at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:316) ~[spigot.jar:git-Spigot-1649]
at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:332) [spigot.jar:git-Spigot-1649]
at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:417) [spigot.jar:git-Spigot-1649]
at org.bukkit.craftbukkit.v1_7_R4.CraftServer.loadPlugin(CraftServer.java:476) [spigot.jar:git-Spigot-1649]
at org.bukkit.craftbukkit.v1_7_R4.CraftServer.enablePlugins(CraftServer.java:394) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.MinecraftServer.n(MinecraftServer.java:360) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.MinecraftServer.g(MinecraftServer.java:334) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.MinecraftServer.a(MinecraftServer.java:290) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.DedicatedServer.init(DedicatedServer.java:210) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.MinecraftServer.run(MinecraftServer.java:458) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.ThreadServerApplication.run(SourceFile:628) [spigot.jar:git-Spigot-1649]
package me.AngryCupcake274.EntityManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.*;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
public class EntityManager extends JavaPlugin implements Listener {
RemoveEntities reme;
CommandHandler comh;
CleanEntities cent;
int loopdelay;
String oneminutemessage;
String oneminutecolor;
String threesecondsmessage;
String threesecondscolor;
String twosecondsmessage;
String twosecondscolor;
String onesecondmessage;
String onesecondcolor;
String finalmessage;
String finalcolor;
String oneMinWarn;
String threeSecWarn;
String twoSecWarn;
String oneSecWarn;
String removeInfo;
String[] worldNames;
Server server = Bukkit.getServer();
ConsoleCommandSender console = server.getConsoleSender();
PluginDescriptionFile pdf = this.getDescription();
String pdfEnable = ChatColor.RED + pdf.getName() + " " + ChatColor.GREEN
+ pdf.getVersion() + ChatColor.AQUA + " Enabled!";
String pdfDisable = ChatColor.RED + pdf.getName() + " " + ChatColor.GREEN
+ pdf.getVersion() + ChatColor.DARK_PURPLE + " Enabled!";
Player cleaner;
int counter = 0;
int totalcounter = 0;
#Override
public void onEnable() {
console.sendMessage(pdfEnable);
BukkitScheduler scheduler = Bukkit.getServer().getScheduler();
saveDefaultConfig();
loadConfiguration();
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
#Override
public void run() {
for (int first = 0; first >= 1; first++) {
cleanUp();
}
}
}, 0L, 12000L);
}
#Override
public void onDisable() {
console.sendMessage(pdfDisable);
}
#SuppressWarnings("deprecation")
public void cleanUp() {
// warn
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(oneMinWarn);
}
console.sendMessage(oneMinWarn);
BukkitScheduler warn3 = Bukkit.getServer().getScheduler();
warn3.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(threeSecWarn);
}
console.sendMessage(threeSecWarn);
}
}, 1220L);
BukkitScheduler warn2 = Bukkit.getServer().getScheduler();
warn2.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(twoSecWarn);
}
console.sendMessage(twoSecWarn);
}
}, 1240L);
BukkitScheduler warn1 = Bukkit.getServer().getScheduler();
warn1.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(oneSecWarn);
}
console.sendMessage(oneSecWarn);
}
}, 1260L);
BukkitScheduler doAction = Bukkit.getServer().getScheduler();
doAction.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
reme.removeEntities();
}
}, 1280L);
}
#SuppressWarnings("deprecation")
public void cleanUpCommand() {
// warn
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(threeSecWarn);
}
console.sendMessage(threeSecWarn);
BukkitScheduler warn2c = Bukkit.getServer().getScheduler();
warn2c.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(twoSecWarn);
}
console.sendMessage(twoSecWarn);
}
}, 20L);
BukkitScheduler warn1c = Bukkit.getServer().getScheduler();
warn1c.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(oneSecWarn);
}
console.sendMessage(oneSecWarn);
}
}, 40L);
BukkitScheduler doAction = Bukkit.getServer().getScheduler();
doAction.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(removeInfo);
}
console.sendMessage(removeInfo);
}
}, 60L);
}
public void cleanUpCommand2() {
BukkitScheduler doAction = Bukkit.getServer().getScheduler();
doAction.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
reme.removeEntities();
}
}, 0L);
}
public void loadConfiguration() {
String ltime = "looptime";
String onemmsg = "oneminute.message";
String onemcolor = "oneminute.color";
String threesmsg = "threeseconds.message";
String threescolor = "threeseconds.color";
String twosmsg = "twoseconds.message";
String twoscolor = "twoseconds.color";
String onesmsg = "onesecond.message";
String onescolor = "onesecond.color";
String fmsg = "final.message";
String fcolor = "final.color";
String arrowr = "arrow";
String boatr = "boat";
String itemr = "dropped_item";
String eggr = "egg";
String enderdragonr = "ender_dragon";
String enderpearlr = "ender_pearl";
String endersignalr = "ender_signal";
String xporbr = "experience_orb";
String fireballr = "fireball";
String fireworkr = "firework";
String fishinghookr = "fishing_hook";
String itemframer = "item_frame";
String leashr = "leash_hitch";
String lightningr = "lightning";
String minecartr = "minecart";
String minecartchestr = "minecart_chest";
String minecartcommandr = "minecart_command";
String minecartfurnacer = "minecart_furnace";
String minecarthopperr = "minecart_hopper";
String minecartmobspawnerr = "minecart_mob_spawner";
String minecarttntr = "minecart_tnt";
String paintingr = "painting";
String primedtntr = "primed_tnt";
String sfireballr = "small_fireball";
String snowballr = "snowball";
String splashpotionr = "splash_potion";
String expbottler = "exp_bottle";
String thrownxpbottler = "thrown_exp_bottle";
String witherskullr = "wither_skull";
getConfig().addDefault(ltime, (10 * 60 * 20));
getConfig().addDefault(onemmsg,
"Ground items will be removed in 1 minute!");
getConfig().addDefault(onemcolor, "AQUA");
getConfig().addDefault(threesmsg,
"Ground items will be removed in 3 seconds!");
getConfig().addDefault(threescolor, "DARK_GREEN");
getConfig().addDefault(twosmsg, "2 seconds!");
getConfig().addDefault(twoscolor, "GOLD");
getConfig().addDefault(onesmsg, "1 second!");
getConfig().addDefault(onescolor, "RED");
getConfig().addDefault(fmsg, "Ground items will be removed!");
getConfig().addDefault(fcolor, "DARK_RED");
getConfig().addDefault(arrowr, true);
getConfig().addDefault(boatr, false);
getConfig().addDefault(itemr, true);
getConfig().addDefault(eggr, true);
getConfig().addDefault(enderdragonr, false);
getConfig().addDefault(enderpearlr, true);
getConfig().addDefault(endersignalr, true);
getConfig().addDefault(xporbr, true);
getConfig().addDefault(fireballr, true);
getConfig().addDefault(fireworkr, true);
getConfig().addDefault(fishinghookr, false);
getConfig().addDefault(itemframer, false);
getConfig().addDefault(leashr, false);
getConfig().addDefault(lightningr, true);
getConfig().addDefault(minecartr, false);
getConfig().addDefault(minecartchestr, false);
getConfig().addDefault(minecartcommandr, false);
getConfig().addDefault(minecartfurnacer, false);
getConfig().addDefault(minecarthopperr, false);
getConfig().addDefault(minecartmobspawnerr, false);
getConfig().addDefault(minecarttntr, false);
getConfig().addDefault(paintingr, false);
getConfig().addDefault(primedtntr, true);
getConfig().addDefault(sfireballr, true);
getConfig().addDefault(snowballr, true);
getConfig().addDefault(splashpotionr, true);
getConfig().addDefault(expbottler, true);
getConfig().addDefault(thrownxpbottler, true);
getConfig().addDefault(witherskullr, true);
getConfig().options().copyDefaults(true);
saveConfig();
loopdelay = getConfig().getInt("looptime");
oneminutemessage = getConfig().getString("oneminute.message");
oneminutecolor = getConfig().getString("oneminute.color");
threesecondsmessage = getConfig().getString("threeseconds.message");
threesecondscolor = getConfig().getString("threeseconds.color");
twosecondsmessage = getConfig().getString("twoseconds.message");
twosecondscolor = getConfig().getString("twoseconds.color");
onesecondmessage = getConfig().getString("onesecond.message");
onesecondcolor = getConfig().getString("onesecond.color");
finalmessage = getConfig().getString("final.message");
finalcolor = getConfig().getString("final.color");
oneMinWarn = ChatColor.valueOf(oneminutecolor) + oneminutemessage;
threeSecWarn = ChatColor.valueOf(threesecondscolor)
+ threesecondsmessage;
twoSecWarn = ChatColor.valueOf(twosecondscolor) + twosecondsmessage;
oneSecWarn = ChatColor.valueOf(onesecondcolor) + onesecondmessage;
removeInfo = ChatColor.valueOf(finalcolor) + finalmessage;
reme.arrow = getConfig().getBoolean("arrow");
reme.boat = getConfig().getBoolean("boat");
reme.droppeditem = getConfig().getBoolean("dropped_item");
reme.egg = getConfig().getBoolean("egg");
reme.enderpearl = getConfig().getBoolean("ender_pearl");
reme.endersignal = getConfig().getBoolean("ender_signal");
reme.experienceorb = getConfig().getBoolean("experience_orb");
reme.fireball = getConfig().getBoolean("fireball");
reme.firework = getConfig().getBoolean("firework");
reme.fishinghook = getConfig().getBoolean("fishing_hook");
reme.itemframe = getConfig().getBoolean("item_frame");
reme.leashhitch = getConfig().getBoolean("leash_hitch");
reme.lightning = getConfig().getBoolean("lightning");
reme.minecart = getConfig().getBoolean("minecart");
reme.minecartchest = getConfig().getBoolean("minecart_chest");
reme.minecartcommand = getConfig().getBoolean("minecart_command");
reme.minecartfurnace = getConfig().getBoolean("minecart_furnace");
reme.minecarthopper = getConfig().getBoolean("minecart_hopper");
reme.minecartmobspawner = getConfig().getBoolean("minecart_mob_spawner");
reme.minecarttnt = getConfig().getBoolean("minecart_tnt");
reme.painting = getConfig().getBoolean("painting");
reme.primedtnt = getConfig().getBoolean("primed_tnt");
reme.smallfireball = getConfig().getBoolean("small_fireball");
reme.snowball = getConfig().getBoolean("snowball");
reme.splashpotion = getConfig().getBoolean("splash_potion");
reme.thrownexpbottle = getConfig().getBoolean("exp_bottle");
reme.witherskull = getConfig().getBoolean("wither_skull");
saveDefaultConfig();
}
public void reloadPlugin() {
reloadConfig();
loopdelay = getConfig().getInt("looptime");
oneminutemessage = getConfig().getString("oneminute.message");
oneminutecolor = getConfig().getString("oneminute.color");
threesecondsmessage = getConfig().getString("threeseconds.message");
threesecondscolor = getConfig().getString("threeseconds.color");
twosecondsmessage = getConfig().getString("twoseconds.message");
twosecondscolor = getConfig().getString("twoseconds.color");
onesecondmessage = getConfig().getString("onesecond.message");
onesecondcolor = getConfig().getString("onesecond.color");
finalmessage = getConfig().getString("final.message");
finalcolor = getConfig().getString("final.color");
reme.arrow = getConfig().getBoolean("arrow");
reme.boat = getConfig().getBoolean("boat");
reme.droppeditem = getConfig().getBoolean("dropped_item");
reme.egg = getConfig().getBoolean("egg");
reme.enderpearl = getConfig().getBoolean("ender_pearl");
reme.endersignal = getConfig().getBoolean("ender_signal");
reme.experienceorb = getConfig().getBoolean("experience_orb");
reme.fireball = getConfig().getBoolean("fireball");
reme.firework = getConfig().getBoolean("firework");
reme.fishinghook = getConfig().getBoolean("fishing_hook");
reme.itemframe = getConfig().getBoolean("item_frame");
reme.leashhitch = getConfig().getBoolean("leash_hitch");
reme.lightning = getConfig().getBoolean("lightning");
reme.minecart = getConfig().getBoolean("minecart");
reme.minecartchest = getConfig().getBoolean("minecart_chest");
reme.minecartcommand = getConfig().getBoolean("minecart_command");
reme.minecartfurnace = getConfig().getBoolean("minecart_furnace");
reme.minecarthopper = getConfig().getBoolean("minecart_hopper");
reme.minecartmobspawner = getConfig().getBoolean("minecart_mob_spawner");
reme.minecarttnt = getConfig().getBoolean("minecart_tnt");
reme.painting = getConfig().getBoolean("painting");
reme.primedtnt = getConfig().getBoolean("primed_tnt");
reme.smallfireball = getConfig().getBoolean("small_fireball");
reme.snowball = getConfig().getBoolean("snowball");
reme.splashpotion = getConfig().getBoolean("splash_potion");
reme.thrownexpbottle = getConfig().getBoolean("exp_bottle");
reme.witherskull = getConfig().getBoolean("wither_skull");
getServer().getScheduler().cancelTasks(this);
getServer().getPluginManager().disablePlugin(this);
getServer().getPluginManager().enablePlugin(this);
}
}

me.AngryCupcake274.EntityManager.EntityManager.loadConfiguration(EntityManager.java:296)
The exception is thrown at line 296 of your EntityManager.java file.
reme.arrow = getConfig().getBoolean("arrow");
At this point of time reme is still null and therefore you can't assign arrow.
You should ensure that RemoveEntitites is already instantiated once you call loadConfiguration() in your onEnable() method.
Also see What is a NPE and how do I fix it?.

I did it!
Instead of setting the RemoveEntities variables, I told the RemoveEntities class to find the variables in the EntityManager class.

Related

APACH POI parsing HTML with JSOUP

Parsing an HTML text constaining <font> tags does not reset the size and family font after </font>
My code works pretty well except after </font>.
Before <font size=9> blablabla.. the text size was 11. I was expecting that after </font> the text size was reset to 11, but it still remains at 9. Same thing for the font family.
Certainly I have misunderstood how to use jsoup. I'd better use CSS, but I don't know how to do.
Thanks for help.
package test;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
import org.apache.poi.xwpf.usermodel.VerticalAlign;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblLayoutType;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblLayoutType;
public class ReadHtml
{
protected static java.util.Vector<String> contenu = null;
org.apache.xmlbeans.XmlCursor cursor = null;
class WStyle
{
protected String police = "Times New Roman";
protected int taille = 11;
protected Color couleur = Color.black;
protected boolean gras = false;
protected boolean italique = false;
public WStyle() // constructeur
{
super();
}
protected String getPolice() {return police;}
protected int getTaille() {return taille;}
protected Color getCouleur() {return couleur;}
protected boolean getGras() {return gras;}
protected boolean getItalique() {return italique;}
protected void setPolice(String p) {police=p;}
protected void setTaille(int t) {taille=t;}
protected void setCouleur(Color c) {couleur=c;}
protected void setGras(boolean g) {gras=g;}
protected void setItalique(boolean i) {italique=i;}
}
public ReadHtml()
{
super();
contenu = new java.util.Vector<String>();
createWordFile();
}
private XWPFParagraph getTableParagraph(XWPFTableCell cell, String html)
{
cell.removeParagraph(0);
XWPFParagraph paragraph = cell.addParagraph();
paragraph.setSpacingAfterLines(0);
paragraph.setSpacingAfter(0);
Document htmlDocument = Jsoup.parse(html);
Elements htmlParagraphs = htmlDocument.select("p");
for(Element htmlParagraph : htmlParagraphs)
{
System.out.println(htmlParagraph);
ParagraphNodeVisitor nodeVisitor = new ParagraphNodeVisitor(paragraph);
NodeTraversor.traverse(nodeVisitor, htmlParagraph);
}
return paragraph;
}
private void createWordFile()
{
XWPFParagraph para = null;
try
{
XWPFDocument document = new XWPFDocument();
FileOutputStream out = new FileOutputStream(new File("./", "NewTable.docx"));
XWPFTable table = document.createTable();
CTTblLayoutType type = table.getCTTbl().getTblPr().addNewTblLayout();
type.setType(STTblLayoutType.FIXED);
table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(1670));
table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(6000));
String myTexte = "<html><head</head><body><p><font face=\"Verdana\" size=11>Good Morning</font> <font size=9 face=\"Times\"> " +
"<i><b>how are you today </b></i></font> Not so bad.<br>Thanks";
// first line
XWPFTableRow tableRow= table.getRow(0);
para = getTableParagraph(tableRow.getCell(0), "<p>Row #1, Col. #1");
tableRow .getCell(0).setParagraph(para);
XWPFTableCell cell = tableRow.createCell();
para = getTableParagraph(cell, myTexte); // Row #1, Col. #2
tableRow .getCell(1).setParagraph(para);
// seconde line
tableRow= table.createRow();
para = getTableParagraph(tableRow.getCell(0), "<p>Row #2, Col. #1");
tableRow .getCell(0).setParagraph(para);
para = getTableParagraph(tableRow.getCell(1), "<p>Row #2, Col. #2");
tableRow.getCell(1).setParagraph(para);
document.write(out);
document.close();
out.close();
System.out.println("NewTable.docx written successully");
}
catch (FileNotFoundException e) {System.out.println("File exception --> " + e.toString()); }
catch (IOException e) {System.out.println("I/O exception --> " + e.toString()); }
catch (Exception e) {System.out.println("Other exception --> " + e.toString()); }
}
public class ParagraphNodeVisitor implements NodeVisitor
{
String nodeName;
String fontFace;
String fontType;
boolean needNewRun;
boolean isItalic;
boolean isBold;
boolean isUnderlined;
int fontSize;
String fontColor;
VerticalAlign align = VerticalAlign.BASELINE ;
XWPFParagraph paragraph;
XWPFRun run;
ParagraphNodeVisitor(XWPFParagraph paragraph)
{
this.paragraph = paragraph;
this.run = paragraph.createRun();
this.nodeName = "";
this.needNewRun = false;
this.isItalic = false;
this.isBold = false;
this.isUnderlined = false;
this.fontSize = 11;
this.fontColor = "000000";
this.fontFace="Times";
}
#Override
public void head(Node node, int depth)
{
nodeName = node.nodeName();
needNewRun = false;
if ("#text".equals(nodeName))
{
run.setText(((TextNode)node).text());
needNewRun = true; //after setting the text in the run a new run is needed
}
else if ("i".equals(nodeName)) {isItalic = true;}
else if ("b".equals(nodeName)) {isBold = true;}
else if ("sup".equals(nodeName)){align = VerticalAlign.SUPERSCRIPT ;}
else if ("u".equals(nodeName)) {isUnderlined = true;}
else if ("br".equals(nodeName)) {run.addBreak();}
else if ("p".equals(nodeName)) {run.addBreak();}
else if ("font".equals(nodeName))
{
fontColor = (!"".equals(node.attr("color")))?node.attr("color").substring(1):"000000";
fontSize = (!"".equals(node.attr("size")))?Integer.parseInt(node.attr("size")):11;
fontFace = (!"".equals(node.attr("face")))?node.attr("face"):"Times";
}
if (needNewRun) run = paragraph.createRun();
needNewRun = false;
run.setItalic(isItalic);
run.setBold(isBold);
if (isUnderlined) run.setUnderline(UnderlinePatterns.SINGLE);
else run.setUnderline(UnderlinePatterns.NONE);
run.setColor(fontColor);
run.setFontSize(fontSize);
run.setFontFamily(fontFace);
run.setSubscript(align);
}
#Override
public void tail(Node node, int depth)
{
nodeName = node.nodeName();
System.out.println("Node=" + nodeName);
if ("i".equals(nodeName)) {isItalic = false;}
else if ("b".equals(nodeName)) {isBold = false;}
else if ("u".equals(nodeName)) {isUnderlined = false;}
else if ("sup".equals(nodeName)) {align= VerticalAlign.BASELINE ;}
else if ("font".equals("nodeName"))
{
fontColor = "000000";
fontSize = 11;
fontFace="Times";
System.out.println("Family=" + fontFace + " Taille=" + fontSize);
}
if (needNewRun) run = paragraph.createRun();
needNewRun = false;
run.setItalic(isItalic);
run.setBold(isBold);
if (isUnderlined) run.setUnderline(UnderlinePatterns.SINGLE); else run.setUnderline(UnderlinePatterns.NONE);
run.setColor(fontColor);
run.setFontSize(fontSize);
run.setFontFamily(fontFace);
run.setSubscript(align);
}
}
public static void main(String[] args)
{
new ReadHtml() ;
}
}
Please change the following line in your tail method, from
else if ("font".equals("nodeName"))
to
else if ("font".equals(nodeName))
You've compared two string literals instead of compare a string literal to the variable. Because of the typo the condition is always false, therefore fontSize is never reseted.

error is occuring while creating custom tokenizer in lucene 7.3

I m trying to create new tokenizer by refering book tamingtext (which uses lucene 3.+ api) using new lucene api 7.3, but it is giving me error as mentioned below
java.lang.IllegalStateException: TokenStream contract violation: reset()/close() call missing, reset() called multiple times, or subclass does not call super.reset(). Please see Javadocs of TokenStream class for more information about the correct consuming workflow.
at org.apache.lucene.analysis.Tokenizer$1.read(Tokenizer.java:109)
at java.io.Reader.read(Reader.java:140)
at solr.SentenceTokenizer.fillSentences(SentenceTokenizer.java:43)
at solr.SentenceTokenizer.incrementToken(SentenceTokenizer.java:55)
at solr.NameFilter.fillSpans(NameFilter.java:56)
at solr.NameFilter.incrementToken(NameFilter.java:88)
at spec.solr.NameFilterTest.testNameFilter(NameFilterTest.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Here is my SentenceTokenizer class
Initializing method, in older api there was super(Reader); but in current api there is no access to Reader class
public SentenceTokenizer(SentenceDetector detector) {
super();
setReader(reader);
this.sentenceDetector = detector;
}
Here is my reset method
#Override
public void reset() throws IOException {
super.reset();
sentenceDetector = null;
}
When i tried to access this method from custom TokenFilter, I m getting above error
public void fillSentences() throws IOException {
char[] c = new char[256];
int size = 0;
StringBuilder stringBuilder = new StringBuilder();
while ((size = input.read(c)) >= 0) {
stringBuilder.append(c, 0, size);
}
String temp = stringBuilder.toString();
inputSentence = temp.toCharArray();
sentenceSpans = sentenceDetector.sentPosDetect(temp);
tokenOffset = 0;
}
#Override
public final boolean incrementToken() throws IOException {
if (sentenceSpans == null) {
//invoking following method
fillSentences();
}
if (tokenOffset == sentenceSpans.length) {
return false;
}
Span sentenceSpan = sentenceSpans[tokenOffset];
clearAttributes();
int start = sentenceSpan.getStart();
int end = sentenceSpan.getEnd();
charTermAttribute.copyBuffer(inputSentence, start, end - start);
positionIncrementAttribute.setPositionIncrement(1);
offsetAttribute.setOffset(start, end);
tokenOffset++;
return true;
}
Here is my custom TokenFilter class
public final class NameFilter extends TokenFilter {
public static final String NE_PREFIX = "NE_";
private final Tokenizer tokenizer;
private final String[] tokenTypeNames;
private final NameFinderME[] nameFinderME;
private final KeywordAttribute keywordAttribute = addAttribute(KeywordAttribute.class);
private final PositionIncrementAttribute positionIncrementAttribute = addAttribute(PositionIncrementAttribute.class);
private final CharTermAttribute charTermAttribute = addAttribute(CharTermAttribute.class);
private final OffsetAttribute offsetAttribute = addAttribute(OffsetAttribute.class);
private String text;
private int baseOffset;
private Span[] spans;
private String[] tokens;
private Span[][] foundNames;
private boolean[][] tokenTypes;
private int spanOffsets = 0;
private final Queue<AttributeSource.State> tokenQueue =
new LinkedList<>();
public NameFilter(TokenStream in, String[] modelNames, NameFinderME[] nameFinderME) {
super(in);
this.tokenizer = SimpleTokenizer.INSTANCE;
this.nameFinderME = nameFinderME;
this.tokenTypeNames = new String[modelNames.length];
for (int i = 0; i < modelNames.length; i++) {
this.tokenTypeNames[i] = NE_PREFIX + modelNames[i];
}
}
//consumes tokens from the upstream tokenizer and buffer them in a
//StringBuilder whose contents will be passed to opennlp
protected boolean fillSpans() throws IOException {
if (!this.input.incrementToken()) return false;
//process the next sentence from the upstream tokenizer
this.text = input.getAttribute(CharTermAttribute.class).toString();
this.baseOffset = this.input.getAttribute(OffsetAttribute.class).startOffset();
this.spans = this.tokenizer.tokenizePos(text);
this.tokens = Span.spansToStrings(spans, text);
this.foundNames = new Span[this.nameFinderME.length][];
for (int i = 0; i < nameFinderME.length; i++) {
this.foundNames[i] = nameFinderME[i].find(tokens);
}
//insize
this.tokenTypes = new boolean[this.tokens.length][this.nameFinderME.length];
for (int i = 0; i < nameFinderME.length; i++) {
Span[] spans = foundNames[i];
for (int j = 0; j < spans.length; j++) {
int start = spans[j].getStart();
int end = spans[j].getEnd();
for (int k = start; k < end; k++) {
this.tokenTypes[k][i] = true;
}
}
}
spanOffsets = 0;
return true;
}
#Override
public boolean incrementToken() throws IOException {
//if there's nothing in the queue
if(tokenQueue.peek()==null){
//no span or spans consumed
if (spans==null||spanOffsets>=spans.length){
if (!fillSpans())return false;
}
if (spanOffsets>=spans.length)return false;
//copy the token and any types
clearAttributes();
keywordAttribute.setKeyword(false);
positionIncrementAttribute.setPositionIncrement(1);
int startOffset = baseOffset +spans[spanOffsets].getStart();
int endOffset = baseOffset+spans[spanOffsets].getEnd();
offsetAttribute.setOffset(startOffset,endOffset);
charTermAttribute.setEmpty()
.append(tokens[spanOffsets]);
//determine of the current token is of a named entity type, if so
//push the current state into the queue and add a token reflecting
// any matching entity types.
boolean [] types = tokenTypes[spanOffsets];
for (int i = 0; i < nameFinderME.length; i++) {
if (types[i]){
keywordAttribute.setKeyword(true);
positionIncrementAttribute.setPositionIncrement(0);
tokenQueue.add(captureState());
positionIncrementAttribute.setPositionIncrement(1);
charTermAttribute.setEmpty().append(tokenTypeNames[i]);
}
}
}
spanOffsets++;
return true;
}
#Override
public void close() throws IOException {
super.close();
reset();
}
#Override
public void reset() throws IOException {
super.reset();
this.spanOffsets = 0;
this.spans = null;
}
#Override
public void end() throws IOException {
super.end();
reset();
}
}
here is my test case for following class
#Test
public void testNameFilter() throws IOException {
Reader in = new StringReader(input);
Tokenizer tokenizer = new SentenceTokenizer( detector);
tokenizer.reset();
NameFilter nameFilter = new NameFilter(tokenizer, modelName, nameFinderMES);
nameFilter.reset();
CharTermAttribute charTermAttribute;
PositionIncrementAttribute positionIncrementAttribute;
OffsetAttribute offsetAttribute;
int pass = 0;
while (pass < 2) {
int pos = 0;
int lastStart = 0;
int lastEnd = 0;
//error occur on below invoke
while (nameFilter.incrementToken()) {
}
}
I have added following changes in my code and it work fine but i m now sure it is correct answer
public SentenceTokenizer(Reader reader,SentenceDetector sentenceDetector) {
super();
this.input =reader;
this.sentenceDetector = sentenceDetector;
}

Problems with a JPA query

I have a problem when performing a query in an HQL.
ORM
Persona
#Entity
#Table(name = "persona")
#Inheritance(strategy = InheritanceType.JOINED)
#DynamicUpdate
#SelectBeforeUpdate(value = false)
#SelectBeforeUpdate(value = false)
#NamedQueries({
#NamedQuery(name = "PersonasByRfc", query = "FROM Persona p WHERE p.rfc = :rfc "),
#NamedQuery(name = "PersonasPorTipoPersona", query = "FROM Persona p WHERE p.tipoPersona = :tipoPersona "),
#NamedQuery(name = "PersonaByClienteId", query = " SELECT c.persona FROM Cliente c WHERE c.clienteId = :clienteId "),
#NamedQuery(name = "PersonaMoralActiva", query = "SELECT c.persona FROM Cliente c WHERE c.persona.regimenFiscal = 'MORAL' AND c.estatus = 'ACTIVO' ")
})
public class Persona extends CommonBusinessProperties {
private static final long serialVersionUID = 2846894501470704239L;
private Long personaId;
private CatTipoPersona tipoPersona;
private String descripcionTipoPersona;
private String nombres;
private String apellidoMaterno;
private String apellidoPaterno;
private RegimenFiscal regimenFiscal;
private Nacionalidad nacionalidad;
private String rfc;
private String curp;
private Genero genero;
private Date fechaNacimiento;
private Boolean esCliente;
private Boolean esContratante;
private Boolean esPagador;
private Boolean esMontoPagar;
private BigDecimal montoPagar;
private Boolean esPorcentajePagar;
private String porcentajePagar;
private String origenPersona;
private String parentesco;
private Parentesco tranParentesco;
private Cliente cliente;
private ExpedientePersona expedientePersona;
private List<Domicilio> domicilios = new ArrayList<>(0);
private List<Telefono> telefonos = new ArrayList<>(0);
private List<Correo> correos = new ArrayList<>(0);
/**
* Constructor <br>
* Crea una nueva instancia de Persona. <br>
*
* #author Orlando Adrián Ramos Galván (oramos#legosoft.com.mx, orlandoa.ramos#outlook.com)<br>
*/
public Persona() {
super();
}
/**
* Constructor <br>
* Crea una nueva instancia de Persona. <br>
*
* #param personaId
* #author Orlando Adrián Ramos Galván (oramos#legosoft.com.mx, orlandoa.ramos#outlook.com)<br>
*/
public Persona(Long personaId) {
super();
this.personaId = personaId;
}
/**
* Constructor <br>
* Crea una nueva instancia de Persona. <br>
*
* #param personaBuilder
* #author Orlando Adrián Ramos Galván (oramos#legosoft.com.mx, orlandoa.ramos#outlook.com)<br>
*/
public Persona(PersonaBuilder personaBuilder) {
this.tipoPersona = personaBuilder.getTipoPersona();
this.descripcionTipoPersona = personaBuilder.getDescripcionTipoPersona();
this.nombres = personaBuilder.getNombresORazonSocial();
this.apellidoMaterno = personaBuilder.getApellidoMaterno();
this.apellidoPaterno = personaBuilder.getApellidoPaterno();
this.setRegimenFiscal(personaBuilder.getRegimenFiscal());
this.setNacionalidad(personaBuilder.getNacionalidad());
this.setRfc(personaBuilder.getRfc());
this.curp = personaBuilder.getCurp();
this.genero = personaBuilder.getGenero();
this.fechaNacimiento = personaBuilder.getFechaNacimiento();
this.esCliente = personaBuilder.getEsCliente();
this.esContratante = personaBuilder.getEsContratante();
this.esPagador = personaBuilder.getEsPagador();
this.esMontoPagar = personaBuilder.getEsMontoPagar();
this.montoPagar = personaBuilder.getMontoPagar();
this.esPorcentajePagar = personaBuilder.getEsPorcentajePagar();
this.porcentajePagar = personaBuilder.getPorcentajePagar();
this.domicilios = personaBuilder.getDomicilios();
this.telefonos = personaBuilder.getTelefonos();
this.correos = personaBuilder.getCorreos();
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "persona_id", unique = true, nullable = false, updatable = false)
public Long getPersonaId() {
return this.personaId;
}
public void setPersonaId(Long personaId) {
this.personaId = personaId;
}
#ManyToOne(fetch = FetchType.EAGER, targetEntity = CatTipoPersona.class)
#JoinColumn(name = "tipo_persona_id")
#Fetch(FetchMode.SELECT)
public CatTipoPersona getTipoPersona() {
return this.tipoPersona;
}
public void setTipoPersona(CatTipoPersona tipoPersona) {
this.tipoPersona = tipoPersona;
}
#Column(name = "tipo_persona", length = 50)
public String getDescripcionTipoPersona() {
return this.descripcionTipoPersona;
}
public void setDescripcionTipoPersona(String tipoPersona) {
this.descripcionTipoPersona = tipoPersona;
}
#Column(name = "origen_persona", length = 50)
public String getOrigenPersona() {
return this.origenPersona;
}
#Column(name = "nombres", length = 100)
public String getNombresORazonSocial() {
return this.nombres;
}
public void setNombresORazonSocial(String nombres) {
this.nombres = nombres;
}
#Column(name = "apellido_materno", length = 100)
public String getApellidoMaterno() {
return this.apellidoMaterno;
}
public void setApellidoMaterno(String apellidoMaterno) {
this.apellidoMaterno = apellidoMaterno;
}
#Column(name = "apellido_paterno", length = 100)
public String getApellidoPaterno() {
return this.apellidoPaterno;
}
public void setApellidoPaterno(String apellidoPaterno) {
this.apellidoPaterno = apellidoPaterno;
}
#Transient
public String getNombreCompleto() {
return this.nombres + " " + this.apellidoMaterno + " " + this.apellidoPaterno;
}
#Column(name = "regimen_fiscal", length = 100)
#Enumerated(EnumType.STRING)
public RegimenFiscal getRegimenFiscal() {
return this.regimenFiscal;
}
public void setRegimenFiscal(RegimenFiscal regimenFiscal) {
this.regimenFiscal = regimenFiscal;
}
#Column(name = "nacionalidad", length = 100)
#Enumerated(EnumType.STRING)
public Nacionalidad getNacionalidad() {
return this.nacionalidad;
}
public void setNacionalidad(Nacionalidad nacionalidad) {
this.nacionalidad = nacionalidad;
}
#Column(name = "rfc", length = 13)
public String getRfc() {
return this.rfc;
}
public void setRfc(String rfc) {
this.rfc = rfc;
}
#Column(name = "curp", length = 45)
public String getCurp() {
return this.curp;
}
public void setCurp(String curp) {
this.curp = curp;
}
#Column(name = "genero", length = 1)
#Convert(converter = GeneroConverter.class)
public Genero getGenero() {
return this.genero;
}
public void setGenero(Genero genero) {
this.genero = genero;
}
#Temporal(TemporalType.DATE)
#Column(name = "fecha_nacimiento", length = 10)
public Date getFechaNacimiento() {
return this.fechaNacimiento;
}
public void setFechaNacimiento(Date fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
#Column(name = "es_cliente")
public Boolean isCliente() {
return this.esCliente;
}
public void setIsCliente(Boolean esCliente) {
this.esCliente = esCliente;
}
#Column(name = "es_contratante")
public Boolean esContratante() {
return this.esContratante;
}
public void setEsContratante(Boolean esContratante) {
this.esContratante = esContratante;
}
#Column(name = "es_pagador")
public Boolean isEsPagador() {
return this.esPagador;
}
public void setEsPagador(Boolean esPagador) {
this.esPagador = esPagador;
}
#Column(name = "es_monto_pagar")
public Boolean getEsMontoPagar() {
return this.esMontoPagar;
}
public void setEsMontoPagar(Boolean esMontoPagar) {
this.esMontoPagar = esMontoPagar;
}
#Column(name = "monto_pagar", precision = 16, scale = 4)
public BigDecimal getMontoPagar() {
return this.montoPagar;
}
public void setMontoPagar(BigDecimal montoPagar) {
this.montoPagar = montoPagar;
}
#Column(name = "es_porcentaje_pagar")
public Boolean getEsPorcentajePagar() {
return this.esPorcentajePagar;
}
public void setEsPorcentajePagar(Boolean esPorcentajePagar) {
this.esPorcentajePagar = esPorcentajePagar;
}
#Column(name = "porcentaje_pagar", length = 6)
public String getPorcentajePagar() {
return this.porcentajePagar;
}
public void setPorcentajePagar(String porcentajePagar) {
this.porcentajePagar = porcentajePagar;
}
public void setOrigenPersona(String origenPersona) {
this.origenPersona = origenPersona;
}
#OneToOne(fetch = FetchType.EAGER, mappedBy = "persona", targetEntity = ExpedientePersona.class, optional = true)
protected ExpedientePersona getExpedientePersona() {
return this.expedientePersona;
}
protected void setExpedientePersona(ExpedientePersona expedientePersonas) {
this.expedientePersona = expedientePersonas;
}
/**
* #return parentesco
*/
#Column(name = "parentesco", length = 50)
public String getParentesco() {
return parentesco;
}
/**
* #param parentesco
*/
public void setParentesco(String parentesco) {
this.parentesco = parentesco;
}
#OneToOne(fetch = FetchType.EAGER, mappedBy = "persona", targetEntity = Cliente.class, cascade = {
CascadeType.MERGE, CascadeType.DETACH })
#Fetch(FetchMode.SELECT)
public Cliente getCliente() {
return this.cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
/**
* #return si la persona esta relacionada al contratante y es una familiar este campo idnica que
* parentesco tienen.
*/
#Transient
public Parentesco getTranParentesco() {
return tranParentesco;
}
/**
* #param tranParentesco
*/
public void setTranParentesco(Parentesco tranParentesco) {
this.tranParentesco = tranParentesco;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "persona", targetEntity = Domicilio.class, cascade = {
CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE, CascadeType.REFRESH })
#Fetch(FetchMode.SELECT)
#OrderBy
protected List<Domicilio> getDomicilios() {
return this.domicilios;
}
protected void setDomicilios(List<Domicilio> domicilios) {
this.domicilios = domicilios;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "persona", targetEntity = Telefono.class, cascade = {
CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE, CascadeType.REFRESH })
#Fetch(FetchMode.SELECT)
#OrderBy
protected List<Telefono> getTelefonos() {
return this.telefonos;
}
protected void setTelefonos(List<Telefono> telefonos) {
this.telefonos = telefonos;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "persona", targetEntity = Correo.class, cascade = {
CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE, CascadeType.REFRESH })
#Fetch(FetchMode.SELECT)
#OrderBy
protected List<Correo> getCorreos() {
return this.correos;
}
protected void setCorreos(List<Correo> correos) {
this.correos = correos;
}
}

With Lucene 4.3.1, How to get all terms which occur in sub-range of all docs

Suppose a lucene index with fields : date, content.
I want to get all terms value and frequency of docs whose date is yesterday. date field is keyword field. content field is analyzed and indexed.
Pls help me with sample code.
My solution source is as follow ...
/**
*
*
* #param reader
* #param fromDateTime
* - yyyymmddhhmmss
* #param toDateTime
* - yyyymmddhhmmss
* #return
*/
static public String top10(IndexSearcher searcher, String fromDateTime,
String toDateTime) {
String top10Query = "";
try {
Query query = new TermRangeQuery("tweetDate", new BytesRef(
fromDateTime), new BytesRef(toDateTime), true, false);
final BitSet bits = new BitSet(searcher.getIndexReader().maxDoc());
searcher.search(query, new Collector() {
private int docBase;
#Override
public void setScorer(Scorer scorer) throws IOException {
}
#Override
public void setNextReader(AtomicReaderContext context)
throws IOException {
this.docBase = context.docBase;
}
#Override
public void collect(int doc) throws IOException {
bits.set(doc + docBase);
}
#Override
public boolean acceptsDocsOutOfOrder() {
return false;
}
});
//
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43,
EnglishStopWords.getEnglishStopWords());
//
HashMap<String, Long> wordFrequency = new HashMap<>();
for (int wx = 0; wx < bits.length(); ++wx) {
if (bits.get(wx)) {
Document wd = searcher.doc(wx);
//
TokenStream tokenStream = analyzer.tokenStream("temp",
new StringReader(wd.get("content")));
// OffsetAttribute offsetAttribute = tokenStream
// .addAttribute(OffsetAttribute.class);
CharTermAttribute charTermAttribute = tokenStream
.addAttribute(CharTermAttribute.class);
tokenStream.reset();
while (tokenStream.incrementToken()) {
// int startOffset = offsetAttribute.startOffset();
// int endOffset = offsetAttribute.endOffset();
String term = charTermAttribute.toString();
if (term.length() < 2)
continue;
Long wl;
if ((wl = wordFrequency.get(term)) == null)
wordFrequency.put(term, 1L);
else {
wl += 1;
wordFrequency.put(term, wl);
}
}
tokenStream.end();
tokenStream.close();
}
}
analyzer.close();
// sort
List<String> occurterm = new ArrayList<String>();
for (String ws : wordFrequency.keySet()) {
occurterm.add(String.format("%06d\t%s", wordFrequency.get(ws),
ws));
}
Collections.sort(occurterm, Collections.reverseOrder());
// make query string by top 10 words
int topCount = 10;
for (String ws : occurterm) {
if (topCount-- == 0)
break;
String[] tks = ws.split("\\t");
top10Query += tks[1] + " ";
}
top10Query.trim();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
// return top10 word string
return top10Query;
}

To display an album art from media store in android

I'm not able to display album art from media store while listing albums,I'm getting
error
Bad request for field slot 0,-1. numRows = 32, numColumns = 7
01-02 02:48:16.789: D/AndroidRuntime(4963): Shutting down VM
01-02 02:48:16.789: W/dalvikvm(4963): threadid=1: thread exiting with uncaught exception (group=0x4001e578)
01-02 02:48:16.804: E/AndroidRuntime(4963): FATAL EXCEPTION: main
01-02 02:48:16.804: E/AndroidRuntime(4963): java.lang.IllegalStateException: get field slot from row 0 col -1 failed
Can anyone kindly help with this issue,Thanks in advance
public class AlbumbsListActivity extends Activity {
private ListAdapter albumListAdapter;
private HashMap<Integer, Integer> albumInfo;
private HashMap<Integer, Integer> albumListInfo;
private HashMap<Integer, String> albumListTitleInfo;
private String audioMediaId;
private static final String TAG = "AlbumsListActivity";
Boolean showAlbumList = false;
Boolean AlbumListTitle = false;
ImageView album_art ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.albums_list_layout);
Cursor cursor;
ContentResolver cr = getApplicationContext().getContentResolver();
if (getIntent().hasExtra(Util.ALBUM_ID)) {
int albumId = getIntent().getIntExtra(Util.ALBUM_ID,
Util.MINUS_ONE);
String[] projection = new String[] { Albums._ID, Albums.ALBUM, Albums.ARTIST, Albums.ALBUM_ART, Albums.NUMBER_OF_SONGS };
String selection = null;
String[] selectionArgs = null;
String sortOrder = Media.ALBUM + " ASC";
cursor = cr.query(Albums.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, sortOrder);
/* final String[] ccols = new String[] {
//MediaStore.Audio.Albums.,
MediaStore.Audio.Albums._ID,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Albums.ARTIST,
MediaStore.Audio.Albums.ALBUM_ART,
MediaStore.Audio.Albums.NUMBER_OF_SONGS
};
cursor = cr.query(MediaStore.Audio.Albums.getContentUri(
"external"), ccols, null, null,
MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);*/
showAlbumList = true;
}
else
{
String order = MediaStore.Audio.Albums.ALBUM + " ASC";
String where = MediaStore.Audio.Albums.ALBUM;
cursor = managedQuery(Media.EXTERNAL_CONTENT_URI,
DbUtil.projection, null, null, order);
showAlbumList = false;
}
albumInfo = new HashMap<Integer, Integer>();
albumListInfo = new HashMap<Integer, Integer>();
ListView listView = (ListView) findViewById(R.id.mylist_album);
listView.setFastScrollEnabled(true);
listView.setOnItemLongClickListener(new ItemLongClickListener());
listView.setAdapter(new AlbumCursorAdapter(this, cursor,
DbUtil.displayFields, DbUtil.displayViews,showAlbumList));
final Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
final Cursor albumListCursor = cr.query(uri, DbUtil.Albumprojection,
null, null, null);
}
private class AlbumCursorAdapter extends SimpleCursorAdapter implements SectionIndexer{
private final Context context;
private final Cursor cursorValues;
private Time musicTime;
private Boolean isAlbumList;
private MusicAlphabetIndexer mIndexer;
private int mTitleIdx;
public AlbumCursorAdapter(Context context, Cursor cursor, String[] from,
int[] to,Boolean isAlbumList) {
super(context, 0, cursor, from, to);
this.context = context;
this.cursorValues = cursor;
//musicTime = new Time();
this.isAlbumList = isAlbumList;
}
String albumName="";
String artistName = "";
String numberofsongs = "";
long albumid;
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater
.inflate(R.layout.row_album_layout, parent, false);
}
this.cursorValues.moveToPosition(position);
String title = "";
String artistName = "";
String albumName = "";
int count;
long albumid = 0;
String songDuration = "";
if (isAlbumList) {
albumInfo.put(
position,
Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums._ID))));
artistName = this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ARTIST));
albumName = this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ALBUM));
albumid=Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ID)));
} else {
albumInfo.put(position, Integer.parseInt(this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media._ID))));
artistName = this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
albumName = this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
albumid=Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
}
//code for Alphabetical Indexer
mTitleIdx = cursorValues.getColumnIndex(MediaStore.Audio.Media.ALBUM);
mIndexer = new MusicAlphabetIndexer(cursorValues, mTitleIdx,
getResources().getString(R.string.fast_scroll_alphabet));
//end
TextView metaone = (TextView) rowView.findViewById(R.id.album_name);
TextView metatwo = (TextView) rowView.findViewById(R.id.artist_name);
ImageView metafour = (ImageView) rowView.findViewById(R.id.album_art);
TextView metathree = (TextView) rowView
.findViewById(R.id.songs_count);
metaone.setText(albumName);
metatwo.setText(artistName);
(metafour)getAlbumArt(albumid);
System.out.println("albumid----------"+albumid);
metaThree.setText(DbUtil.makeTimeString(context, secs));
getAlbumArt(albumid);
}
TextView metaone = (TextView) rowView.findViewById(R.id.album_name);
TextView metatwo = (TextView) rowView.findViewById(R.id.artist_name);
album_art = (ImageView) rowView.findViewById(R.id.album_art);
//TextView metathree = (TextView) rowView.findViewById(R.id.songs_count);
metaone.setText(albumName);
metatwo.setText(artistName);
return rowView;
}
}
String albumArtUri = "";
private void getAlbumArt(long albumid) {
Uri uri=ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumid);
System.out.println("hhhhhhhhhhh" + uri);
Cursor cursor = getContentResolver().query(
ContentUris.withAppendedId(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumid),
new String[] { MediaStore.Audio.AlbumColumns.ALBUM_ART },
null,
null,
null);
if (cursor.moveToFirst()) {
albumArtUri = cursor.getString(0);
}
System.out.println("kkkkkkkkkkkkkkkkkkk :" + albumArtUri);
cursor.close();
if(albumArtUri != null){
Options opts = new Options();
opts.inJustDecodeBounds = true;
Bitmap albumCoverBitmap = BitmapFactory.decodeFile(albumArtUri, opts);
opts.inJustDecodeBounds = false;
albumCoverBitmap = BitmapFactory.decodeFile(albumArtUri, opts);
if(albumCoverBitmap != null)
album_art.setImageBitmap(albumCoverBitmap);
}else {
// TODO:
Options opts = new Options();
Bitmap albumCoverBitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.albumart_mp_unknown_list, opts);
if(albumCoverBitmap != null)
album_art.setImageBitmap(albumCoverBitmap);
}
}
}
}