Java.lang.NullpointException error on Java Applet Initialization - applet

I've done some searching on these types of errors and still can't quite figure out what I'm doing wrong. My Applet won't start/initialize. The applet window pops up and then says Start: applet not initialized at the bottom.
Here are the errors:
java.lang.NullPointerException
at randomquotegenerator.quote.init(quote.java:170)
at sun.applet.AppletPanel.run(AppletPanel.java:424)
at java.lang.Thread.run(Thread.java:619)
The line that's coming back as erroring for quote.java:170 is in the init() section:
readLines(quoteFiles[0].getName());
I have 7 text files with quotes in them, one per each line and the first line is the title for the quotes. Each line is surrounded by double quotes "".
//****************************************************************************
//****************************************************************************
//** Imports **
//****************************************************************************
package randomquotegenerator;
import java.io.*;
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
//****************************************************************************
//** Class Definination **
//****************************************************************************
public class quote extends JApplet implements ActionListener,Runnable
{
//****************************************************************************
//** Class Global Variables **
//****************************************************************************
int randomLine=0,maxLines=0,maxFiles=0,quoteLine=0,quoteFile=0;
int doneFiles[] =new int[100];
int doneLines[] =new int[200];
int randomSwitch=-1,linearSwitch=-1;
int TimeDelay=0,TimeWait=1;
int currentFile=0,currentLine=0,unreadLines=0,unreadFiles=0;
//int randomFile,randomLine;
File path=new File("quotes\\");
File[] quoteFiles=path.listFiles();
Thread thread;
Panel northPanel=new Panel();
Panel centerPanel=new Panel();
Panel southPanel=new Panel(new GridLayout(1,0));
Panel Labels = new Panel(new GridLayout(0,1));
Panel ListBox1 = new Panel(new GridLayout(1,0));
Panel ListBox2 = new Panel(new GridLayout(1,0));
Panel ButtonSet1 = new Panel(new GridLayout(3,2));
Panel ButtonSet2 = new Panel(new GridLayout(0,1));
JLabel lab1=new JLabel("Quote Files");
JLabel lab2=new JLabel("Current File");
JLabel lab3=new JLabel("Quote Lines ");
JLabel lab4=new JLabel("Current Line");
JLabel lab5=new JLabel("TimeDelay ");
JLabel lab6=new JLabel(" ");
JLabel lab7=new JLabel(" ");
List FilesList=new List(7);
List LinesList=new List(7);
JTextArea quoteDisplay= new JTextArea(18,36);
JLabel quoteTitle = new JLabel("Java Applet Random Quote Displayer");
Button PrevLine=new Button("Prev Line");
Button NextLine=new Button("Next Line");
Button PrevFile=new Button("Prev File");
Button NextFile=new Button("Next File");
Button ResetLine=new Button("Reset Lines");
Button ResetFile=new Button("Reset Files");
Button Settings=new Button("Settings ");
Button NullButton1=new Button(" ");
Button LinearButton=new Button("Linear Mode");
Button RandomButton=new Button("Random Mode");
Button ExitButton=new Button("Exit");
boolean done=false;
//String s=new String;;
String lines[]=new String[200];
//****************************************************************************
//** Inititialize
//****************************************************************************
#Override
public void init(){
setSize(768, 500);
setLayout(new BorderLayout());
add("North",northPanel);
northPanel.setBackground(Color.blue);
add("Center",centerPanel);
centerPanel.setBackground(Color.black);
add("South",southPanel);
southPanel.setBackground(new Color(64,64,64));
northPanel.setBackground(new Color(64,64,64));
Labels.add(lab1);
Labels.add(lab2);
Labels.add(lab3);
Labels.add(lab4);
Labels.add(lab5);
Labels.add(lab6);
Labels.add(lab7);
ListBox1.add(FilesList);
ListBox2.add(LinesList);
ButtonSet1.add(PrevLine);
ButtonSet1.add(NextLine);
ButtonSet1.add(PrevFile);
ButtonSet1.add(NextFile);
ButtonSet1.add(ResetLine);
ButtonSet1.add(ResetFile);
//ButtonSet1.add(Settings);
//ButtonSet1.add(NullButton1);
ButtonSet2.add(LinearButton);
ButtonSet2.add(RandomButton);
ButtonSet2.add(ExitButton);
southPanel.add(Labels);
southPanel.add(ListBox1);
southPanel.add(ListBox2);
southPanel.add(ButtonSet1);
southPanel.add(ButtonSet2);
centerPanel.add(quoteDisplay);
northPanel.add(quoteTitle);
//quoteDisplay.setColor(new Color(255,255,255));
FilesList.addActionListener(this);
LinesList.addActionListener(this);
PrevLine.addActionListener(this);
NextLine.addActionListener(this);
PrevFile.addActionListener(this);
NextFile.addActionListener(this);
ResetLine.addActionListener(this);
ResetFile.addActionListener(this);
Settings.addActionListener(this);
//NullButton1.addActionListener(this);
LinearButton.addActionListener(this);
RandomButton.addActionListener(this);
ExitButton.addActionListener(this);
Font font=new Font("times",Font.BOLD,24);
quoteDisplay.setFont(font);
quoteDisplay.setEditable(false);
quoteDisplay.setLineWrap(true);
quoteDisplay.setWrapStyleWord(true);
Font font2=new Font("times",Font.BOLD,16);
quoteTitle.setFont(font2);
listFiles();
readLines(quoteFiles[0].getName());
FilesList.select(0);
LinesList.select(0);
TimeDelay=lines[0].length()*TimeWait;
unreadFiles=maxFiles;
unreadLines=maxLines;
currentFile=0;
currentLine=0;
done=false;
//maxLines=10;
creatRandomFiles();
creatRandomLines();
lab1.setText("quote Files = "+maxFiles);
lab2.setText("File = "+quoteFiles[0].getName());
lab3.setText("quote Lines = "+maxLines);
lab4.setText("Current Line = "+quoteLine);
lab5.setText("TimeDelay = "+TimeDelay);
lab6.setText("Lines Unread "+unreadLines);
lab7.setText("Files Unread "+unreadFiles);
JOptionPane.showMessageDialog(null, " By Erin");
}
//*********************************************
//* *
//*********************************************
public void creatRandomFiles()
{
for (int i=0;i<maxFiles;i++)
{
doneFiles[i]=(int)(Math.random()*maxFiles);
for(int j=0;j<i;j++) if (doneFiles[j]==doneFiles[i]) i--;
//System.out.println("maxLines = "+doneLines[i]+"");
}
}
//*********************************************
//* *
//*********************************************
public void creatRandomLines()
{
for (int i=0;i<maxLines;i++)
{
doneLines[i]=(int)(Math.random()*maxLines);
for(int j=0;j<i;j++) if (doneLines[j]==doneLines[i]) i--;
//System.out.println("maxLines = "+doneLines[i]+"");
}
}
//*********************************************
//* *
//*********************************************
public void runLinearLines()
{
while(currentLine<maxLines)
{
quoteLine=currentLine;
selectLine();
TimeDelay=lines[quoteLine].length()*TimeWait;
unreadLines=maxLines-currentLine;
lab5.setText("TimeDelay = "+TimeDelay);
lab6.setText("Lines Unread "+unreadLines);
currentLine++;
System.out.println("Line Data: "+ (currentLine+1)+ ". Line= "+doneLines[currentLine]+ ", Unread= "+ unreadLines+" ,time=" +TimeDelay+" ms");
try {thread.sleep(TimeDelay);}
catch (Exception exception){}
}
currentLine=0;
quoteLine=0;
unreadLines=maxLines-currentLine;
currentFile++;
unreadFiles=maxFiles-currentFile;
quoteFile=currentFile;
FilesList.select(quoteFile);
//FilesList.makeVisible(quoteFile);
readLines(quoteFiles[FilesList.getSelectedIndex()].getName());
lab6.setText("Lines Unread "+unreadLines);
lab2.setText("File = "+quoteFiles[FilesList.getSelectedIndex()].getName());
lab7.setText("Files Unread "+unreadFiles);
System.out.println("-------------------------------------------------------------");
System.out.println("File Data: "+ (currentFile+1)+ ", " + quoteFiles[FilesList.getSelectedIndex()].getName()+". File= "+doneFiles[currentFile]+" ,time=" +TimeDelay+" ms");
System.out.println("-------------------------------------------------------------");
if (unreadFiles<0)
{
currentFile=0;
currentLine=0;
}
}
//*********************************************
//* *
//*********************************************
public void runRandomLines()
{
//currentLine=0;
while(currentLine<maxLines)
{
quoteLine=doneLines[currentLine];
selectLine();
TimeDelay=lines[quoteLine].length()*TimeWait;
unreadLines=maxLines-currentLine;
lab5.setText("TimeDelay = "+TimeDelay);
lab6.setText("Lines Unread "+unreadLines);
currentLine++;
System.out.println("Line Data: "+ (currentLine+1)+ ". Line= "+doneLines[currentLine]+ ", Unread= "+ unreadLines+" ,time=" +TimeDelay+" ms");
try {thread.sleep(TimeDelay);}catch (Exception exception){}
}
currentLine=0;
quoteLine=0;
unreadLines=maxLines-currentLine;
currentFile++;
unreadFiles=maxFiles-currentFile;
quoteFile=doneFiles[currentFile];
FilesList.select(quoteFile);
//FilesList.makeVisible(quoteFile);
for (int i=0;i<200;i++) doneLines[i]=0;
creatRandomLines();
readLines(quoteFiles[FilesList.getSelectedIndex()].getName());
lab6.setText("Lines Unread "+unreadLines);
lab2.setText("File = "+quoteFiles[FilesList.getSelectedIndex()].getName());
lab7.setText("Files Unread "+(unreadFiles+1));
System.out.println("-------------------------------------------------------------");
System.out.println("File Data: "+ (currentFile+1)+ ", " + quoteFiles[FilesList.getSelectedIndex()].getName()+". File= "+doneFiles[currentFile]+" ,time=" +TimeDelay+" ms");
System.out.println("-------------------------------------------------------------");
if (unreadFiles<0)
{
for (int i=0;i<100;i++) doneFiles[i]=0;
for (int i=0;i<200;i++) doneLines[i]=0;
creatRandomFiles();
creatRandomLines();
currentFile=0;
currentLine=0;
}
//System.out.println("------------------------------");
}
//****************************************************************************
//** Paint **
//****************************************************************************
#Override
public void paint(Graphics g)
{
}
//****************************************************************************
//** Thread **
//****************************************************************************
#Override
public void start()
{
thread = new Thread(this);
thread.start();
}
#Override
synchronized public void run()
{
while (true)
{
//*********************************************
//* *
//*********************************************
if (randomSwitch==1)
{
creatRandomLines();
runRandomLines();
}
if (linearSwitch==1)
{
runLinearLines();
}
}
}
#Override
public void stop()
{
if (thread != null) thread.stop();
}
//****************************************************************************
//** actionPerformed **
//****************************************************************************
public void selectFile()
{
for (int i=0;i<200;i++) doneLines[i]=0;
FilesList.select(quoteFile);
//FilesList.makeVisible(quoteFile);
readLines(quoteFiles[FilesList.getSelectedIndex()].getName());
lab2.setText("File = "+quoteFiles[FilesList.getSelectedIndex()].getName());
}
//*********************************************
//* *
//*********************************************
public void selectLine()
{
LinesList.select(quoteLine);
//LinesList.makeVisible(quoteLine);
quoteDisplay.setText(lines[LinesList.getSelectedIndex()]);
lab4.setText("Current Line = "+(quoteLine+1));
TimeDelay=lines[quoteLine].length()*TimeWait;
lab5.setText("TimeDelay = "+TimeDelay);
}
//*********************************************
//* *
//*********************************************
#Override
public boolean keyDown(Event event, int key)
{
switch(key)
{
case 10:
//enter
break;
case 32:
//space
break;
case 27:
//esc
System.exit(0);
break;
case 1006:
//left
done=true;
quoteLine=0;
quoteFile--;if (quoteFile<1) quoteFile=0;
selectFile();
selectLine();
break;
case 1007:
//right
done=true;
quoteLine=0;
quoteFile++;if (quoteLine>maxFiles) quoteFile=maxFiles;
selectFile();
selectLine();
break;
case 1004:
//up
quoteLine--;if (quoteLine<1) quoteLine=0;
selectLine();
break;
case 1005:
//down
quoteLine++;if (quoteLine>maxLines) quoteLine=maxLines;
selectLine();
break;
}
showStatus("(key= "+key+") ");
return false;
}
//*********************************************
//* *
//*********************************************
#Override
public void actionPerformed(ActionEvent event)
{
if (event.getSource()==ExitButton)
{
//System.exit(0);
}
if (event.getSource()==LinesList)
{
quoteLine=LinesList.getSelectedIndex();
showStatus(FilesList.getSelectedItem()+" " +LinesList.getSelectedItem()+ " "+ LinesList.getSelectedIndex());
quoteDisplay.setText(lines[LinesList.getSelectedIndex()]);
lab4.setText("Current Line = "+(quoteLine+1));
//quoteTitle.setText(lines[LinesList.getSelectedIndex()]);
}
if (event.getSource()==FilesList)
{
quoteFile=FilesList.getSelectedIndex();
lab2.setText("File = "+quoteFiles[FilesList.getSelectedIndex()].getName());
showStatus(FilesList.getSelectedItem()+" " +LinesList.getSelectedItem()+ " "+ LinesList.getSelectedIndex());
readLines(quoteFiles[FilesList.getSelectedIndex()].getName());
quoteLine=0;
//selectFile();
selectLine();
}
if (event.getSource()==PrevLine)
{
quoteLine--;if (quoteLine<1) quoteLine=0;
selectLine();
}
if (event.getSource()==NextLine)
{
quoteLine++;if (quoteLine>maxLines) quoteLine=maxLines;
selectLine();
}
if (event.getSource()==PrevFile)
{
done=true;
quoteLine=0;
quoteFile--;if (quoteFile<1) quoteFile=0;
selectFile();
selectLine();
}
if (event.getSource()==NextFile)
{
done=true;
quoteLine=0;
quoteFile++;if (quoteLine>maxFiles) quoteFile=maxFiles;
selectFile();
selectLine();
}
if (event.getSource()==ResetLine)
{
quoteLine=0;
quoteFile=0;
selectFile();
selectLine();
}
if (event.getSource()==ResetFile)
{
quoteLine=0;
quoteFile=0;
selectFile();
selectLine();
}
if (event.getSource()==LinearButton)
{
linearSwitch=-linearSwitch;
if (linearSwitch==1)
{
randomSwitch=-1;
LinearButton.setLabel("Linear Off ");
RandomButton.setLabel("Random On");
}
else
{
LinearButton.setLabel("Linear On");
}
System.out.println("linearSwitch = " + linearSwitch+", randomSwitch= "+randomSwitch);
}
if (event.getSource()==RandomButton)
{
randomSwitch=-randomSwitch;
if (randomSwitch==1)
{
linearSwitch =-1;
RandomButton.setLabel("Random Off ");
LinearButton.setLabel("Linear On");
}
else
{
RandomButton.setLabel("Random On");
}
System.out.println("linearSwitch = " + linearSwitch+", randomSwitch= "+randomSwitch);
}
if (event.getSource()==ExitButton)
{
System.exit(0);
}
}
//*********************************************
//* *
//*********************************************
public void readLines(String fileName)
{
DataInputStream inStream;
int count=0;
LinesList.removeAll();
try {
inStream = new DataInputStream(
new FileInputStream("quotes\\"+fileName));
while ( inStream.available() > 0 )
{
lines[count]=inStream.readLine();
if (count==0)
{
quoteTitle.setText(lines[count]);
quoteDisplay.setText(lines[count]);
}
LinesList.add((count+1) + "");
// System.out.println( lines[count]);
count++;
} // End while.
maxLines=count;
lab3.setText("quote Lines = "+maxLines);
inStream.close();
} catch ( java.io.IOException exception)
{
if ( exception instanceof FileNotFoundException)
{
System.out.println(
"A file called test.txt could not be found, \n" +
"or could not be opened.\n" +
"Please investigate and try again.");
}
}
}
//*********************************************
//* *
//*********************************************
public void listFiles()
{
int i;
maxFiles=0;
if (quoteFiles !=null)
{
for (i=0;i<quoteFiles.length;i++)
{
// System.out.println(" "+i +" " + quoteFiles[i]);
FilesList.add(quoteFiles[i].getName());
maxFiles++;
}
lab1.setText("quote Files = "+maxFiles);
}
}
//****************************************************************************
//** **
//****************************************************************************
}

File path=new File("quotes\\");
File[] quoteFiles=path.listFiles();
path could be returning null.
Try declaring it, then initializing it in the init().
If it is null, then the quoteFiles would be empty, because listFiles() most likely has a catch on it, so path would be null.
Tell me if this helps :D
Firexranger8

Related

Passing values from android to flutter but not from main activity

i'm implementing a third party android sdk in flutter and i want a message to be passed from android to flutter when sdk starts
i have implemented the sdk using platform channel just need to work on the callback code. In the code there is a function called onChannelJoin i want to send message to flutter when this function is called
Main Activity
public class MainActivity extends FlutterActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
final String CHANNEL = "samples.flutter.io/screen_record";
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
#Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
// TODO
if (call.method.equals("startScreenShare")) {
Intent intent = new Intent(MainActivity.this , HelloAgoraScreenSharingActivity.class);
startActivity(intent);
} else {
result.notImplemented();
}
}
});
}
}
ScreenSharingActivity
public class HelloAgoraScreenSharingActivity extends Activity {
private static final String LOG_TAG = "AgoraScreenSharing";
private static final int PERMISSION_REQ_ID_RECORD_AUDIO = 22;
private ScreenCapture mScreenCapture;
private GLRender mScreenGLRender;
private RtcEngine mRtcEngine;
private boolean mIsLandSpace = false;
private void initModules() {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (mScreenGLRender == null) {
mScreenGLRender = new GLRender();
}
if (mScreenCapture == null) {
mScreenCapture = new ScreenCapture(getApplicationContext(), mScreenGLRender, metrics.densityDpi);
}
mScreenCapture.mImgTexSrcConnector.connect(new SinkConnector<ImgTexFrame>() {
#Override
public void onFormatChanged(Object obj) {
Log.d(LOG_TAG, "onFormatChanged " + obj.toString());
}
#Override
public void onFrameAvailable(ImgTexFrame frame) {
Log.d(LOG_TAG, "onFrameAvailable " + frame.toString());
if (mRtcEngine == null) {
return;
}
AgoraVideoFrame vf = new AgoraVideoFrame();
vf.format = AgoraVideoFrame.FORMAT_TEXTURE_OES;
vf.timeStamp = frame.pts;
vf.stride = frame.mFormat.mWidth;
vf.height = frame.mFormat.mHeight;
vf.textureID = frame.mTextureId;
vf.syncMode = true;
vf.eglContext14 = mScreenGLRender.getEGLContext();
vf.transform = frame.mTexMatrix;
mRtcEngine.pushExternalVideoFrame(vf);
}
});
mScreenCapture.setOnScreenCaptureListener(new ScreenCapture.OnScreenCaptureListener() {
#Override
public void onStarted() {
Log.d(LOG_TAG, "Screen Record Started");
}
#Override
public void onError(int err) {
Log.d(LOG_TAG, "onError " + err);
switch (err) {
case ScreenCapture.SCREEN_ERROR_SYSTEM_UNSUPPORTED:
break;
case ScreenCapture.SCREEN_ERROR_PERMISSION_DENIED:
break;
}
}
});
WindowManager wm = (WindowManager) getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE);
int screenWidth = wm.getDefaultDisplay().getWidth();
int screenHeight = wm.getDefaultDisplay().getHeight();
if ((mIsLandSpace && screenWidth < screenHeight) ||
(!mIsLandSpace) && screenWidth > screenHeight) {
screenWidth = wm.getDefaultDisplay().getHeight();
screenHeight = wm.getDefaultDisplay().getWidth();
}
setOffscreenPreview(screenWidth, screenHeight);
if (mRtcEngine == null) {
try {
mRtcEngine = RtcEngine.create(getApplicationContext(), "Agora_id", new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
Log.d(LOG_TAG, "onJoinChannelSuccess " + channel + " " + elapsed);
}
#Override
public void onWarning(int warn) {
Log.d(LOG_TAG, "onWarning " + warn);
}
#Override
public void onError(int err) {
Log.d(LOG_TAG, "onError " + err);
}
#Override
public void onAudioRouteChanged(int routing) {
Log.d(LOG_TAG, "onAudioRouteChanged " + routing);
}
});
} catch (Exception e) {
Log.e(LOG_TAG, Log.getStackTraceString(e));
throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
}
mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING);
mRtcEngine.enableVideo();
if (mRtcEngine.isTextureEncodeSupported()) {
mRtcEngine.setExternalVideoSource(true, true, true);
} else {
throw new RuntimeException("Can not work on device do not supporting texture" + mRtcEngine.isTextureEncodeSupported());
}
mRtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_360P, true);
mRtcEngine.setClientRole(Constants.CLIENT_ROLE_BROADCASTER);
}
}
private void deInitModules() {
RtcEngine.destroy();
mRtcEngine = null;
if (mScreenCapture != null) {
mScreenCapture.release();
mScreenCapture = null;
}
if (mScreenGLRender != null) {
mScreenGLRender.quit();
mScreenGLRender = null;
}
}
/**
* Set offscreen preview.
*
* #param width offscreen width
* #param height offscreen height
* #throws IllegalArgumentException
*/
public void setOffscreenPreview(int width, int height) throws IllegalArgumentException {
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Invalid offscreen resolution");
}
mScreenGLRender.init(width, height);
}
private void startCapture() {
mScreenCapture.start();
}
private void stopCapture() {
mScreenCapture.stop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_agora_screen_sharing);
}
public void onLiveSharingScreenClicked(View view) {
Button button = (Button) view;
boolean selected = button.isSelected();
button.setSelected(!selected);
if (button.isSelected()) {
initModules();
startCapture();
String channel = "ss_test" + System.currentTimeMillis();
channel = "ss_test";
button.setText("stop");
mRtcEngine.muteAllRemoteAudioStreams(true);
mRtcEngine.muteAllRemoteVideoStreams(true);
mRtcEngine.joinChannel(null, channel, "", 0);
} else {
button.setText("start");
mRtcEngine.leaveChannel();
stopCapture();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
deInitModules();
}
}
Dart Code
const platform = const MethodChannel('samples.flutter.io/screen_record');
try {
final int result = await platform.invokeMethod('startScreenShare');
} on PlatformException catch (e) {}
setState(() {
});

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

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(){
...

Why does setText in the TextField doesn't work?

Why does this method doesn't save the new selected categories. is there something wrong with my codes?
catCon = new TextField();
rowEditing.addEditor(catConfig, catCon);
this is the code for setting the catCon:
TextButton save = new TextButton("Save");
save.addSelectHandler(new SelectEvent.SelectHandler() {
#Override
public void onSelect(SelectEvent event) {
selectedItems = new LinkedList<Short>();
for (int i = 0; i < toCat.size(); i++) {
selectedItems.add(toCat.get(i).getIDCategory());
}
Collections.sort(selectedItems);
newSelectedItems = selectedItems.toString().replace(",", "-").replace("[", "").replace("]", "").replace(" ", "");
msg = new MessageBox("SELECTED ITEMSSSSSSSSS: " + selectedItems.size() + " " + newSelectedItems);;
msg.show();
catCon.setText(newSelectedItems);
hide();
}
});
and this is where the saving of the commited changes:
rowEditing.getSaveButton().addSelectHandler(new SelectEvent.SelectHandler() {
#Override
public void onSelect(SelectEvent event) {
store.commitChanges();
service.saveUserRights(store.get(index), new AsyncCallback<Boolean>() {
#Override
public void onFailure(Throwable caught) {
msg = new MessageBox("Error", caught.getMessage());
msg.show();
}
#Override
public void onSuccess(Boolean result) {
if (result) {
msg = new MessageBox("Information", "Changes saved.");
msg.show();
service.getURListGrid(new AsyncCallback<List<UserRights>>() {
#Override
public void onFailure(Throwable caught) {
MessageBox msg = new MessageBox("Error", caught.getMessage());
msg.show();
}
#Override
public void onSuccess(List<UserRights> result) {
store = new ListStore<UserRights>(properties.idRight());
store.addAll(result);
grid.reconfigure(store, cm);
}
});
} else {
msg = new MessageBox("Error", "Failed to save changes.");
msg.show();
}
}
});
}
});
When I am going to set the catCon there will no be changes of the data but when I manually type the categories there will be a change. Can somebody help me?
In order for me to save the current categories is to get the index of the store and set the category to the newSelectedItem
store.get(index).setCategories(newSelectedItems);
I hope this will help to the people who has the same problem as mine.

Enabling single column selection in org.eclipse.swt.widgets.Table

I have used the org.eclipse.swt.widgets.Table
Code implementation will look like this
Table table = new Table(shell, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
But i need behavior like if mouse clicked on 'Sec_1' i want only 'Sec_1' to be selected not entire row and if mouse clicked on 'First_1' i don't want it to be Highlighted(FirstColumn no selection).
Can any one help me ?
Please see this code snippet for example (http://git.eclipse.org/c/platform/eclipse.platform.ui.git/tree/examples/org.eclipse.jface.snippets/Eclipse%20JFace%20Snippets/org/eclipse/jface/snippets/viewers/Snippet036FocusBorderCellHighlighter.java):
public class Test {
private class MyContentProvider implements IStructuredContentProvider {
/*
* (non-Javadoc)
*
* #see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
public Object[] getElements(Object inputElement) {
return (MyModel[]) inputElement;
}
/*
* (non-Javadoc)
*
* #see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
public void dispose() {
}
/*
* (non-Javadoc)
*
* #see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
* java.lang.Object, java.lang.Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
public static boolean flag = true;
public class MyModel {
public int counter;
public MyModel(int counter) {
this.counter = counter;
}
public String toString() {
return "Item " + this.counter;
}
}
public class MyLabelProvider extends LabelProvider implements
ITableLabelProvider, ITableFontProvider, ITableColorProvider {
FontRegistry registry = new FontRegistry();
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
return "Column " + columnIndex + " => " + element.toString();
}
public Font getFont(Object element, int columnIndex) {
return null;
}
public Color getBackground(Object element, int columnIndex) {
return null;
}
public Color getForeground(Object element, int columnIndex) {
return null;
}
}
public Test(Shell shell) {
final TableViewer v = new TableViewer(shell, SWT.BORDER|SWT.FULL_SELECTION);
v.setLabelProvider(new MyLabelProvider());
v.setContentProvider(new MyContentProvider());
v.setCellEditors(new CellEditor[] { new TextCellEditor(v.getTable()), new TextCellEditor(v.getTable()), new TextCellEditor(v.getTable()) });
v.setCellModifier(new ICellModifier() {
public boolean canModify(Object element, String property) {
return true;
}
public Object getValue(Object element, String property) {
return "Column " + property + " => " + element.toString();
}
public void modify(Object element, String property, Object value) {
}
});
v.setColumnProperties(new String[] {"1","2","3"});
TableViewerFocusCellManager focusCellManager = new TableViewerFocusCellManager(v,new FocusCellOwnerDrawHighlighter(v));
ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(v) {
protected boolean isEditorActivationEvent(
ColumnViewerEditorActivationEvent event) {
return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
|| (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED && event.keyCode == SWT.CR)
|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
}
};
TableViewerEditor.create(v, focusCellManager, actSupport, ColumnViewerEditor.TABBING_HORIZONTAL
| ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
| ColumnViewerEditor.TABBING_VERTICAL | ColumnViewerEditor.KEYBOARD_ACTIVATION);
TableColumn column = new TableColumn(v.getTable(), SWT.NONE);
column.setWidth(200);
column.setMoveable(true);
column.setText("Column 1");
column = new TableColumn(v.getTable(), SWT.NONE);
column.setWidth(200);
column.setMoveable(true);
column.setText("Column 2");
column = new TableColumn(v.getTable(), SWT.NONE);
column.setWidth(200);
column.setMoveable(true);
column.setText("Column 3");
MyModel[] model = createModel();
v.setInput(model);
v.getTable().setLinesVisible(true);
v.getTable().setHeaderVisible(true);
}
private MyModel[] createModel() {
MyModel[] elements = new MyModel[10];
for (int i = 0; i < 10; i++) {
elements[i] = new MyModel(i);
}
return elements;
}
/**
* #param args
*/
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
new Test(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}

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