Why I get null.pointer exception, I am sure where aren't any null variables - sockets

public class Server {
public static Maze lab;
public static Socket s;
public static Socket z;
public static player human;
public static BufferedReader input;
public static OutputStream os;
public static InputStream is;
public static int n=-1;
public static connections info;
public static ObjectOutputStream oos;
public static void main(String[] args) {
try{
ServerSocket Serversocket = new ServerSocket(1900);
System.out.println("Maze Game Server Started on port " + Serversocket.getLocalPort());
FileInputStream fis = new FileInputStream("labirintas.cfg");
ObjectInputStream ois = new ObjectInputStream(fis);
lab = (Maze) ois.readObject();
fis.close();
ois.close();
info = new connections();
try {
while(true){
try{
s = Serversocket.accept();
z = Serversocket.accept();
System.out.println("Conection from: " + s.getLocalAddress().getHostAddress());
os = s.getOutputStream();
is = z.getInputStream();
oos = new ObjectOutputStream(os);
oos.writeObject(lab);
oos.flush();
n++;
//is.close();
human = new player(n);
human.start();
}catch(Exception exception){
System.out.println("nėra labirinto" + exception.getMessage());
System.exit(0);
}finally
{
s.close();
}
}
} catch ( Exception ex) {
System.out.println(ex.getMessage());
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public static class player extends Thread{
public int x=0;
public int y=0;
public int counter = 0;
public String nick="";
public player(int n){
x=0;
y=0;
counter = n;
try{
input = new BufferedReader(new InputStreamReader(is));
nick = input.readLine();
System.out.println(counter+" "+x+" "+y+" "+ nick );
info.info(counter, x, y, nick);
oos.writeObject(info);
oos.flush();
}catch(Exception e){
System.out.println(e.getStackTrace());
}
}
public int getcooX(){
return x;
}
public int getcooY(){
return y;
}
public void moveUP(){
x--;
}
public void moveDOWN(){
x++;
}
public void moveLEFT(){
y--;
}
public void moveRIGHT(){
y++;
}
#Override
public void run(){
try{
while(true){
System.out.println(s + " with name: "+ nick + ": " + (s.isConnected()?"true":"false"));
if (input!=null){
String command = input.readLine();
System.out.println(command);
if(command.startsWith("MOVE_UP")){
System.out.println("up move");
if (lab.checkUP(x, y)==false){
System.out.println("up accepted");
x--;
info.info(counter, x, y, nick);
oos.writeObject(info);
oos.flush();
}
if(lab.isItWin(x, y)){
System.out.println("Winner");
s.close();
}
}
else if(command.startsWith("MOVE_LEFT")){
System.out.println("left move");
if (lab.checkLEFT(x, y)==false){
System.out.println("left accepted");
y--;
info.info(counter, x, y, nick);
oos.writeObject(info);
oos.flush();
}
if(lab.isItWin(x, y)){
System.out.println("Winner");
s.close();
}
}
else if(command.startsWith("MOVE_RIGHT")){
System.out.println("right move");
if (lab.checkRIGHT(x, y)==false){
System.out.println("right accepted");
y++;
info.info(counter, x, y, nick);
oos.writeObject(info);
oos.flush();
}
if(lab.isItWin(x, y)){
System.out.println("Winner");
s.close();
}
}
else if(command.startsWith("MOVE_DOWN")){
System.out.println("down move");
if (lab.checkRIGHT(x, y)==false){
System.out.println("down accepted");
y++;
info.info(counter, x, y, nick);
oos.writeObject(info);
oos.flush();
}
if(lab.isItWin(x, y)){
System.out.println("Winner");
s.close();
}
}
}
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
}
Why do I get java.lang.NullPointerException? I think I'm doing everything right. I don't understand why I get this.
here the client, and the connections classes.
public class Client implements ActionListener, Serializable{
public static JFrame main;
public static JPanel mainP;
public static JLabel text;
public static JButton New;
public static JButton exit;
public static JTextField nickas;
public JPanel labirintas;
public JMenuBar bar;
public JMenu file;
public JMenu edit;
public JMenuItem close;
public JFrame kurti;
public JLabel[][] label;
public JFrame zaidimas;
public static Maze lab;
public Color sienos = Color.BLACK;
public Color zaidejo = Color.RED;
public Color laimejimo = Color.GREEN;
public Color laukeliai = Color.WHITE;
public int cooX = 0;
public int cooY = 0;
public static PrintWriter output;
public static Socket s;
public static Socket f;
public static connections info;
public static InputStream os;
public static ObjectInputStream oos;
public static void main(String[] args) {
main = new JFrame("Pagrindinis meniu");
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainP = new JPanel();
text = new JLabel("Sveiki čia labirinto žaidimas. Įveskite savo vardą. Pasirinkite ką"
+ " darysite", SwingConstants.CENTER);
text.setVerticalAlignment(SwingConstants.TOP);
New = new JButton("Pradėti žaidimą");
nickas = new JTextField();
nickas.setDocument(new JTextFieldLimit(10));
mainP.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,0,0,0);
mainP.add(text, c);
c.gridx=0;
c.gridy = 1;
mainP.add(nickas, c);
c.gridx = 0;
c.gridy = 2;
mainP.add(New, c);
exit = new JButton("Išeiti iš žaidimo");
c.gridx = 0;
c.gridy = 3;
mainP.add(exit, c);
main.add(mainP);
main.setSize(500, 500);
main.show();
New.addActionListener(new Client());
exit.addActionListener(new Client());
}
#Override
public void actionPerformed(ActionEvent e){
Object source =e.getActionCommand();
if (source.equals("Pradėti žaidimą")){
String nick = nickas.getText();
try{
if(nick.isEmpty()){
JOptionPane.showMessageDialog(main, "Enter Your name", "Please Enter Your name", JOptionPane.ERROR_MESSAGE);
}
else{
s = new Socket("localhost",1900);
f = new Socket("localhost",1900);
os = s.getInputStream();
oos = new ObjectInputStream(os);
lab = (Maze) oos.readObject();
OutputStream is = f.getOutputStream();
//os.close();
output = new PrintWriter(is, true);
main.show(false);
zaidimas =new JFrame("Labirinto kurimas");//sukuriu nauja frame labirinto zaidimui
zaidimas.setLayout(new GridBagLayout());
zaidimas.setBackground(Color.BLACK);
GridBagConstraints ck = new GridBagConstraints(); //sukuriu nauja GridBagConstraints stiliui kurti
/////////////////////
zaidimas.setSize(1200, 600);
bar = new JMenuBar();//meniu juosta
file = new JMenu("File");
edit = new JMenu("Edit");
/////////////////////
bar.add(file);
bar.add(edit);
file.add(close = new JMenuItem("Close"));
close.setAccelerator(KeyStroke.getKeyStroke('C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
//////////////////
JMenuItem spalvos = new JMenuItem("Spalvų meniu");
edit.add(spalvos);
spalvos.setAccelerator(KeyStroke.getKeyStroke('P', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
/////////////////
ck.gridx = 0;//pridedu ja i tokias koordinates
ck.gridy = 0;
ck.fill = GridBagConstraints.HORIZONTAL;//issitemptu horizontaliai
ck.anchor = GridBagConstraints.NORTHWEST;
ck.gridwidth = 4;
ck.weightx = 1.0;
ck.weighty = 0.0;
zaidimas.add(bar, ck);
/////////////////////
labirintas = new JPanel();//labirinto panele
labirintas.setLayout(new GridLayout(lab.h,lab.v));
ck.gridy = 1;
ck.weightx = 0.8;
ck.weighty = 1.0;
ck.fill = GridBagConstraints.BOTH;
zaidimas.add(labirintas, ck);
/////////////////////
text = new JLabel("Online:");
ck.gridx = 4;
ck.weightx = 0.2;
ck.weighty=1.0;
ck.fill = GridBagConstraints.BOTH;
ck.anchor = GridBagConstraints.FIRST_LINE_START;
zaidimas.add(text, ck);
////////
label = new JLabel[lab.h][lab.v];//sukuriu masyva labeliu
////////////////
sienos();
///////////////
label[0][0].setBackground(zaidejo);
///////////////
try{
output.println(nick);
online();
}catch(Exception b){
}
zaidimas.addKeyListener(new KeyListener(){
#Override
public void keyReleased(KeyEvent K){
try{
if (K.getKeyCode()==KeyEvent.VK_A){
output.println("MOVE_LEFT");
output.flush();
if (lab.checkLEFT(cooX, cooY)==false){
label[cooX][cooY].setBackground(Color.white);
cooY--;
online();
}
if(lab.isItWin(cooX, cooY)){
JOptionPane.showMessageDialog(main, "Winner!", "You Won.", JOptionPane.PLAIN_MESSAGE);
System.out.println("Winner");
s.close();
f.close();
System.exit(0);
}
}
else if (K.getKeyCode()==KeyEvent.VK_W){
output.println("MOVE_UP");
output.flush();
if (lab.checkUP(cooX, cooY)==false){
label[cooX][cooY].setBackground(Color.white);
cooX--;
online();
}
if(lab.isItWin(cooX, cooY)){
JOptionPane.showMessageDialog(main, "Winner!", "You Won.", JOptionPane.PLAIN_MESSAGE);
System.out.println("Winner");
s.close();
f.close();
System.exit(0);
}
}
else if (K.getKeyCode()==KeyEvent.VK_D){
output.println("MOVE_RIGHT");
output.flush();
if (lab.checkRIGHT(cooX, cooY)==false){
label[cooX][cooY].setBackground(Color.white);
cooY++;
online();
}
if(lab.isItWin(cooX, cooY)){
JOptionPane.showMessageDialog(main, "Winner!", "You Won.", JOptionPane.PLAIN_MESSAGE);
System.out.println("Winner");
s.close();
f.close();
System.exit(0);
}
}
if (K.getKeyCode()==KeyEvent.VK_S){
output.println("MOVE_DOWN");
output.flush();
if (lab.checkDOWN(cooX, cooY)==false){
label[cooX][cooY].setBackground(Color.white);
cooX++;
online();
}
if(lab.isItWin(cooX, cooY)){
JOptionPane.showMessageDialog(main, "Winner!", "You Won.", JOptionPane.PLAIN_MESSAGE);
System.out.println("Winner");
s.close();
f.close();
System.exit(0);
}
}
}catch(Exception ex){
}
}
public void keyPressed(KeyEvent key){}
public void keyTyped(KeyEvent keyE){}
});
///////////////
zaidimas.show();
close.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
zaidimas.dispose();
main.dispose();
System.exit(0);
}
});
zaidimas.addWindowListener(new WindowAdapter(){
#Override
public void windowClosing(WindowEvent wind){
main.show(true);
mainP.show(true);
try{
s.close();
f.close();
}catch(Exception ex){
}
}
});
}
}catch(UnknownHostException exception){
JOptionPane.showMessageDialog(main, exception.getMessage()+exception, "Host error", JOptionPane.ERROR_MESSAGE);
exception.getStackTrace();
}
catch(Exception except){
JOptionPane.showMessageDialog(main, except.getMessage()+except, "Fatal error", JOptionPane.ERROR_MESSAGE);
except.getStackTrace();
}
}
else if (source.equals("Išeiti iš žaidimo")){
main.dispose();
System.exit(0);
}
}
// public void gamer(){//tikrina ar zaidejas yra laimejimo langelija
// label[game.getcooX()][game.getcooY()].setBackground(zaidejo);
// if (lab.isItWin(game.getcooX(), game.getcooY())){
// zaidimas.dispose();
// JOptionPane.showMessageDialog(main, "Jūs laimėjote!", "Sveikiname", JOptionPane.ERROR_MESSAGE);
// main.show(true);
// mainP.show(true);
// }
// }
public void sienos(){
for(int i=0;i<lab.h;i++){
for(int j=0; j<lab.v;j++){//ciklas braizyti sienom
label[i][j] = new JLabel();
int t=0,r=0,bot=0,l = 0;//i sias reiksmes isirasysiu sienu ploti
if (i==0){
if(lab.checkUP(i, j)) t=5; //tikrina ar borderis, jei borderis, tai storesne siena, jei ne, tai plonesne
}
else {
if(lab.checkUP(i, j)) t=2;
}
if (i==lab.h-1){
if(lab.checkDOWN(i, j)) bot=5;
}
else{
if(lab.checkDOWN(i, j)) bot=2;
}
if(j==lab.v-1){
if(lab.checkRIGHT(i, j)) r=5;
}
else{
if(lab.checkRIGHT(i, j)) r=2;
}
if (j==0){
if(lab.checkLEFT(i, j)) l=5;
}
else{
if(lab.checkLEFT(i, j)) l=2;
}
label[i][j].setBorder(BorderFactory.createMatteBorder(t, l, bot,r , sienos));
label[i][j].setOpaque(true); //kad matytusi labelis
if(lab.isItWin(i, j)) label[i][j].setBackground(laimejimo);
else label[i][j].setBackground(laukeliai);
labirintas.add(label[i][j]);
}
}
}
public void online(){
try{
info = (connections) oos.readObject();
}catch(Exception e){
System.out.println(e.getCause());}
text.setText("Online:");
for (int i=0;i<info.names.length;i++){
text.setText(text.getText() + "\n" + info.names[i]);
label[info.x[i]][info.y[i]].setBackground(Color.gray);
if(lab.isItWin(info.x[i], info.y[i])) label[info.x[i]][info.y[i]].setBackground(laimejimo);
label[cooX][cooX].setBackground(Color.white);
}
}
}
public class connections {
public String[] names;
public int[] x;
public int[] y;
public void connections(){
names = new String[99];
x = new int[99];
y = new int[99];
for (int i=0;i<100;i++){
names[i]="";
x[i]=0;
y[i]=0;
}
}
public void info(int n,int x,int y,String name){
names[n]=name;
this.x[n]=x;
this.y[n]=y;
}
}
Here's what I get from stacktrace:
java.lang.NullPointerException
at client.connections.info(connections.java:24)
at server.Server$player.<init>(Server.java:90)
at server.Server.main(Server.java:57)

The class connections does not have a constructor so the variable names never gets initialized. So when you call the method info and it tries to set names[n]=name it throws a NullPointerException because names is still null.
It looks like you have a constructor because you have a method named connections which is the same as the class name. However, you gave the method a return type of void which prevents it from being a constructor as constructors do not have a return type.
Change that line to:
public class connections {
public connections(){
...
You will now get a NullPointerException because you are attempting to set the 100th location of your names array in your constructor of the connections class.
You create the names array with length 99.
Then your for loop iterates through the numbers 0 through 99 (less than 100).
The problem is that the highest allowable index of names is 98 which is the 99th location. So when you try to set names[99] = "" it throws a NullPointerException.
Change your for loop to only go up to 99 instead of 100:
public connections(){
names = new String[99];
x = new int[99];
y = new int[99];
for (int i=0;i<99;i++){
names[i]="";
x[i]=0;
y[i]=0;
}
}
Or change the arrays to be length 100 to match the for loop:
public connections(){
names = new String[100];
x = new int[100];
y = new int[100];
for (int i=0;i<100;i++){
names[i]="";
x[i]=0;
y[i]=0;
}
}
Java Class Names
In Java the convention is to name all classes with mixed case with the first letter capitalized. See Java Naming Convention
Methods should be name with mixed case with the first letter lowercase.
You should change your connections class as follows:
public class Connections {
public Connections(){
...

Related

I can not Pie Chart entry converting from sql. I need your help for my android application

My application this code.
public float yvalue;
public String xvalue;
public void QuerySQL(String COMANDOSQL) {
ResultSet rs;
try {
Statement statement = connect.createStatement();
rs = statement.executeQuery(COMANDOSQL);
while (rs.next()) {
yvalue = rs.getInt( "ORAN" );
xvalue = rs.getString( "URUNGRUBU" );
pieEntries.add(new PieEntry(yvalue, xvalue)); /// this code does not fill pieEntry
}
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
pieChart.setUsePercentValues(true);
pieDataSet = new PieDataSet(pieEntries,label);
pieData = new PieData(pieDataSet);
pieData.setDrawValues(true);
pieChart.setData(pieData);
pieChart.invalidate();
pieChart.setBackgroundColor( Color.TRANSPARENT);
pieDataSet.setColors(ColorTemplate.COLORFUL_COLORS);
moveoffScreen();
}

Background Service displays a timeout exception after some time in Android 6

This is a service running in the background, no Activity, began operating normally, but After about four hours, there will be a ConnectTimeoutException.
Connect to xxx.xxx.xxx.xxx time out.
This problem occurs in Android 6, I did not find this issue Android 4. When this problem occurs, I have to restart this phone, after which it connects properly for some time. When this problem occurs, other network applications on the phone runs properly.
public class mService extends Service{
Intent intent;
private Handler objHandlerCheckNetwork = new Handler();
private boolean mReflectFlg = false;
private static final int NOTIFICATION_ID = 101;
private static final Class<?>[] mSetForegroundSignature = new Class[] { boolean.class };
private static final Class<?>[] mStartForegroundSignature = new Class[] { int.class , Notification.class };
private static final Class<?>[] mStopForegroundSignature = new Class[] { boolean.class };
private NotificationManager mNM;
private Method mSetForeground;
private Method mStartForeground;
private Method mStopForeground;
private Object[] mSetForegroundArgs = new Object[1];
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];
private Runnable mHttpTestRunnable = new Runnable() {
#Override
public void run() {
if (httpTest()){
Log.e(GlobalData.getClassMethodName(),"true");
}else{
Log.e(GlobalData.getClassMethodName(),"false");
}
}
};
private Runnable mTasksCheckNetwork = new Runnable()
{
public void run()
{
Thread httpTestThread = new Thread(mHttpTestRunnable);;
httpTestThread.start();
objHandlerCheckNetwork.postDelayed(mTasksCheckNetwork, 1000*30);
}
};
#SuppressLint("NewApi")
#Override
public void onCreate() {
super.onCreate();
mNM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE );
try {
mStartForeground = mService.class.getMethod("startForeground" , mStartForegroundSignature);
mStopForeground = mService.class.getMethod("stopForeground" , mStopForegroundSignature);
} catch (NoSuchMethodException e) {
mStartForeground = mStopForeground = null;
}
try {
mSetForeground = getClass().getMethod( "setForeground", mSetForegroundSignature);
} catch (NoSuchMethodException e) {
throw new IllegalStateException( "OS doesn't have Service.startForeground OR Service.setForeground!");
}
Intent intent = new Intent(this,UploadTableDataService.class );
intent.putExtra( "ficationId", NOTIFICATION_ID);
Notification.Builder builder = new Notification.Builder(this);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.gps);
builder.setContentTitle( "test" );
builder.setContentText( "test111" );
Notification notification = builder.getNotification();
startForegroundCompat( NOTIFICATION_ID, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
//startService( new Intent( this, WifiService. class));
//startService( new Intent( this, VoiceService. class));
this.intent = intent;
Log.e(GlobalData.getClassMethodName(),"mService start!");
objHandlerCheckNetwork.postDelayed(mTasksCheckNetwork, 1000);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
try{
objHandlerCheckNetwork.removeCallbacks(mTasksCheckNetwork);
}catch (Exception e) {
Log.d("DEBUG->", "onDestroy error - removeUpdates: ");
}
//stopForegroundCompat( NOTIFICATION_ID);
}
void invokeMethod(Method method, Object[] args) {
try {
method.invoke( this, args);
} catch (InvocationTargetException e) {
// Should not happen.
Log. w("ApiDemos" , "Unable to invoke method" , e);
} catch (IllegalAccessException e) {
// Should not happen.
Log. w("ApiDemos" , "Unable to invoke method" , e);
}
}
/**
* This is a wrapper around the new startForeground method, using the older
* APIs if it is not available.
*/
void startForegroundCompat( int id, Notification notification) {
if ( mReflectFlg) {
// If we have the new startForeground API, then use it.
if ( mStartForeground != null) {
mStartForegroundArgs[0] = Integer. valueOf(id);
mStartForegroundArgs[1] = notification;
invokeMethod( mStartForeground, mStartForegroundArgs);
return;
}
// Fall back on the old API.
mSetForegroundArgs[0] = Boolean. TRUE;
invokeMethod( mSetForeground, mSetForegroundArgs);
mNM.notify(id, notification);
} else {
if (Build.VERSION. SDK_INT >= 5) {
startForeground(id, notification);
} else {
// Fall back on the old API.
mSetForegroundArgs[0] = Boolean. TRUE;
invokeMethod( mSetForeground, mSetForegroundArgs);
mNM.notify(id, notification);
}
}
}
/**
* This is a wrapper around the new stopForeground method, using the older
* APIs if it is not available.
*/
void stopForegroundCompat( int id) {
if ( mReflectFlg) {
// If we have the new stopForeground API, then use it.
if ( mStopForeground != null) {
mStopForegroundArgs[0] = Boolean. TRUE;
invokeMethod( mStopForeground, mStopForegroundArgs);
return;
}
mNM.cancel(id);
mSetForegroundArgs[0] = Boolean. FALSE;
invokeMethod( mSetForeground, mSetForegroundArgs);
} else {
if (Build.VERSION. SDK_INT >= 5) {
stopForeground( true);
} else {
// Fall back on the old API. Note to cancel BEFORE changing the
// foreground state, since we could be killed at that point.
mNM.cancel(id);
mSetForegroundArgs[0] = Boolean. FALSE;
invokeMethod( mSetForeground, mSetForegroundArgs);
}
}
}
public static Boolean httpTest() {
HttpClient client= new DefaultHttpClient();;
try {
StringBuilder sb = new StringBuilder();
HttpParams httpParams = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 1000*5);
HttpConnectionParams.setSoTimeout(httpParams, 1000*10);
HttpResponse response = client.execute(new HttpGet("http://www.itnanny.com/default.htm"));
HttpEntity entity = response.getEntity();
if (entity != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
}
Log.e(GlobalData.getClassMethodName(),"result:"+sb.toString());
if (sb.toString().indexOf("ok") > -1){
return true;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
client.getConnectionManager().shutdown();;
}
return false;
}
}

Creating custom plugin for chinese tokenization

I'm working towards properly integrating the stanford segmenter within SOLR for chinese tokenization.
This plugin involves loading other jar files and model files. I've got it working in a crude manner by hardcoding the complete path for the files.
I'm looking for methods to create the plugin where the paths need not be hardcoded and also to have the plugin in conformance with the SOLR plugin architecture. Please let me know if there are any recommended sites or tutorials for this.
I've added my code below :
public class ChineseTokenizerFactory extends TokenizerFactory {
/** Creates a new WhitespaceTokenizerFactory */
public ChineseTokenizerFactory(Map<String,String> args) {
super(args);
assureMatchVersion();
if (!args.isEmpty()) {
throw new IllegalArgumentException("Unknown parameters: " + args);
}
}
#Override
public ChineseTokenizer create(AttributeFactory factory, Reader input) {
Reader processedStringReader = new ProcessedStringReader(input);
return new ChineseTokenizer(luceneMatchVersion, factory, processedStringReader);
}
}
public class ProcessedStringReader extends java.io.Reader {
private static final int BUFFER_SIZE = 1024 * 8;
//private static TextProcess m_textProcess = null;
private static final String basedir = "/home/praveen/PDS_Meetup/solr-4.9.0/custom_plugins/";
static Properties props = null;
static CRFClassifier<CoreLabel> segmenter = null;
private char[] m_inputData = null;
private int m_offset = 0;
private int m_length = 0;
public ProcessedStringReader(Reader input){
char[] arr = new char[BUFFER_SIZE];
StringBuffer buf = new StringBuffer();
int numChars;
if(segmenter == null)
{
segmenter = new CRFClassifier<CoreLabel>(getProperties());
segmenter.loadClassifierNoExceptions(basedir + "ctb.gz", getProperties());
}
try {
while ((numChars = input.read(arr, 0, arr.length)) > 0) {
buf.append(arr, 0, numChars);
}
} catch (IOException e) {
e.printStackTrace();
}
m_inputData = processText(buf.toString()).toCharArray();
m_offset = 0;
m_length = m_inputData.length;
}
#Override
public int read(char[] cbuf, int off, int len) throws IOException {
int charNumber = 0;
for(int i = m_offset + off;i<m_length && charNumber< len; i++){
cbuf[charNumber] = m_inputData[i];
m_offset ++;
charNumber++;
}
if(charNumber == 0){
return -1;
}
return charNumber;
}
#Override
public void close() throws IOException {
m_inputData = null;
m_offset = 0;
m_length = 0;
}
public String processText(String inputText)
{
List<String> segmented = segmenter.segmentString(inputText);
String output = "";
if(segmented.size() > 0)
{
output = segmented.get(0);
for(int i=1;i<segmented.size();i++)
{
output = output + " " +segmented.get(i);
}
}
System.out.println(output);
return output;
}
static Properties getProperties()
{
if (props == null) {
props = new Properties();
props.setProperty("sighanCorporaDict", basedir);
// props.setProperty("NormalizationTable", "data/norm.simp.utf8");
// props.setProperty("normTableEncoding", "UTF-8");
// below is needed because CTBSegDocumentIteratorFactory accesses it
props.setProperty("serDictionary",basedir+"dict-chris6.ser.gz");
props.setProperty("inputEncoding", "UTF-8");
props.setProperty("sighanPostProcessing", "true");
}
return props;
}
}
public final class ChineseTokenizer extends CharTokenizer {
public ChineseTokenizer(Version matchVersion, Reader in) {
super(matchVersion, in);
}
public ChineseTokenizer(Version matchVersion, AttributeFactory factory, Reader in) {
super(matchVersion, factory, in);
}
/** Collects only characters which do not satisfy
* {#link Character#isWhitespace(int)}.*/
#Override
protected boolean isTokenChar(int c) {
return !Character.isWhitespace(c);
}
}
You can pass the argument through the Factory's args parameter.

JList update freezes display but not JFrame setTitle

If I update a JList with a long number of html formatted items then the controls stop responding and indicators won't update. This makes sense, the event thread is busy. The title can still be set though. Why is this?
Here's some (long) code demonstrating this:
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.*;
public class JListTest extends JFrame {
class TestListModel extends AbstractListModel<String> {
private static final long serialVersionUID = JListTest.serialVersionUID;
private boolean useHtml;
private String[] formattedList = new String[] {};
public int getSize() {
return formattedList.length;
}
public String getElementAt(int index) {
return formattedList[index];
}
public void setUseHtml(boolean useHtml) {
this.useHtml = useHtml;
}
public String getNewListItem() {
if (useHtml) {
return "<html><div style='padding:2px"
+ ";background-color:#EDF5F4;color:black'><div style='padding:2px;font-weight:500;'>"
+ "Item " + (100 * Math.random())
+ "</div>"
+ "This will change!"
+ "</div></html>";
} else {
return "Item " + (100 * Math.random());
}
}
public void updateItems() {
formattedList = new String[] {"<html><h1>Loading!</h1></html>"};
fireContentsChanged(this, 0, 1);
Thread buildItems = new Thread() {
#Override
public void run() {
final String[] tempList = new String[3000];
for (int i=0; i<tempList.length; i++) {
tempList[i] = getNewListItem();
}
// Just show the string bashing's done
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
formattedList = new String[] {"<html><h1>Updating!</h1></html>"};
fireContentsChanged(TestListModel.this, 0, 1);
}
});
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update
SwingUtilities.invokeLater(new Runnable() {
public void run() {
formattedList = tempList;
fireContentsChanged(TestListModel.this, 0, formattedList.length);
}
});
}
};
buildItems.start();
}
}
protected static final long serialVersionUID = 1L;
public JListTest() {
JPanel controlPanel = new JPanel();
JButton updaterControl = new JButton("Add 3000");
final JCheckBox useHtmlControl = new JCheckBox("Use HTML");
final TestListModel model = new TestListModel();
JList<String> list = new JList<String>(model);
JScrollPane scrollPane = new JScrollPane(list);
final JLabel durationIndicator = new JLabel("0");
controlPanel.add(useHtmlControl, BorderLayout.WEST);
controlPanel.add(updaterControl, BorderLayout.EAST);
getContentPane().add(controlPanel, BorderLayout.PAGE_START);
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(durationIndicator, BorderLayout.PAGE_END);
useHtmlControl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.setUseHtml(useHtmlControl.isSelected());
}
});
useHtmlControl.setSelected(false);
updaterControl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.updateItems();
}
});
Timer counter = new Timer();
counter.schedule(new TimerTask() {
#Override
public void run() {
String previousCounter = durationIndicator.getText();
String newCounter = Integer.toString(
Integer.parseInt(previousCounter) + 1);
durationIndicator.setText(newCounter);
setTitle(newCounter);
}
}, 0, 100);
}
public static void main(String args[]) {
JListTest jlt = new JListTest();
jlt.pack();
jlt.setSize(300, 300);
jlt.setVisible( true );
}
}
The answer is pretty obvious - because Window title is not a Swing component, it's OS native entity.
So changes don't have to go through Swing Event Queue, but go to XDecoratedPeer.updateWMName directly in case of Unix and to some other class in other OSes.
The more interesting question would be how to avoid that UI blocking, but I don't think that's possible with just Swing, you'll have to implement some lazy loading, or rendering in batches.

My custome list view not update with new data

Hello I created a custom list view and for update used notifyDataSetChanged() method but my list not updated. please help me.
this is my source code
public class fourthPage extends ListActivity {
ListingFeedParser ls;
List<Listings> data;
EditText SearchText;
Button Search;
private LayoutInflater mInflater;
private ProgressDialog progDialog;
private int pageCount = 0;
String URL;
ListViewListingsAdapter adapter;
Message msg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bundle b = getIntent().getExtras();
URL = b.getString("URL");
Log.i("Ran->URL", "->" + URL);
MYCITY_STATIC_DATA.fourthPage_main_URL = URL;
final ListingFeedParser lf = new ListingFeedParser(URL);
Search = (Button) findViewById(R.id.searchButton);
SearchText = (EditText) findViewById(R.id.search);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(SearchText.getWindowToken(), 0);
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
try {
progDialog = ProgressDialog.show(this, "",
"Loading please wait....", true);
progDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
data = lf.parse();
} catch (Exception e) {
e.printStackTrace();
}
msg = new Message();
msg.what = 1;
fourthPage.this._handle.sendMessage(msg);
}
}).start();
Search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SearchText = (EditText) findViewById(R.id.search);
if (SearchText.getText().toString().equals(""))
return;
CurrentLocationTimer myLocation = new CurrentLocationTimer();
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(final Location location) {
Toast.makeText(
getApplicationContext(),
location.getLatitude() + " "
+ location.getLongitude(),
Toast.LENGTH_LONG).show();
String URL = "http://75.125.237.76/phone_feed_2_point_0_test.php?"
+ "lat="
+ location.getLatitude()
+ "&lng="
+ location.getLongitude()
+ "&page=0&search="
+ SearchText.getText().toString();
Log.e("fourthPage.java Search URL :->", "" + URL);
Bundle b = new Bundle();
b.putString("URL", URL);
Intent it = new Intent(getApplicationContext(),
fourthPage.class);
it.putExtras(b);
startActivity(it);
}
};
myLocation.getLocation(getApplicationContext(),
locationResult);
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"No data available for this request", Toast.LENGTH_LONG)
.show();
}
}
private Handler _handle = new Handler() {
#Override
public void handleMessage(Message msg) {
progDialog.dismiss();
if (msg.what == 1) {
if (data.size() == 0 || data == null) {
Toast.makeText(getApplicationContext(),
"No data available for this request",
Toast.LENGTH_LONG).show();
}
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
adapter = new ListViewListingsAdapter(getApplicationContext(),
R.layout.list1, R.id.title, data, mInflater);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
adapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(),
"Error in retrieving the method", Toast.LENGTH_SHORT)
.show();
}
}
};
public void onListItemClick(ListView parent, View v, int position, long id) {
// remember i m going from bookmark list
MYCITY_STATIC_DATA.come_from_bookmark = false;
Log.i("4thPage.java - MYCITY_STATIC_DATA.come_from_bookmark",
"set false - > check" + MYCITY_STATIC_DATA.come_from_bookmark);
Listings sc = (Listings) this.getListAdapter().getItem(position);
if (sc.getName().equalsIgnoreCase("SEE MORE...")) {
pageCount = pageCount + 1;
final ListingFeedParser lf = new ListingFeedParser((URL.substring(
0, URL.length() - 1)) + pageCount);
try {
progDialog = ProgressDialog.show(this, "",
"Loading please wait....", true);
progDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
data.remove(data.size() - 1);
data.addAll(lf.parse());
Message msg = new Message();
msg.what = 1;
fourthPage.this._handle.sendMessage(msg);
}
}).start();
} catch (Exception e) {
pageCount = pageCount - 1;
// TODO: handle exception
Toast newToast = Toast.makeText(this, "Error in getting Data",
Toast.LENGTH_SHORT);
}
} else {
Bundle b = new Bundle();
b.putParcelable("listing", sc);
Intent it = new Intent(getApplicationContext(),
FifthPageTabbed.class);
it.putExtras(b);
startActivity(it);
}
}
#Override
public void onBackPressed() {
setResult(0);
finish();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.e("RESUME:-)", "4th Page onResume");
try {
//adapter.notifyDataSetChanged();
//setListAdapter(adapter);
//getListView().setTextFilterEnabled(true);
} catch (Exception e) {
Log.e("EXCEPTION in 4th page",
"in onResume msg:->" + e.getMessage());
}
}
}
Do not re-create the object of ArrayList or Array you are passing to adapter, just modify same ArrayList or Array again. and also when array or arrylist size not changed after you modify adapter then in that case notifydatasetchange will not work.
In shot it is work only when array or arraylist size increases or decreases.
What version of Android are you targeting? The latest version seems to have revised how notifyDataSetChanged() works. If you target sdk 11 it might work?
Also, there seems to be a different (and very thorough answer) to this question in another post:
notifyDataSetChanged example