开发者

nullPointerException when passing an arrayList to another function?

in the project im working on, i need to take input from the text box and some selected files from the JFileChooser... i wish to pass the arrayList of files to another class where it has to be processed.. but im getting a nullPointerException here... m new to java so really dont know how to work this out... :-/ plz help!! i have included the indexing class as well:

    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;  //notice javax
    public class home extends JFrame
    {
      JLabel lab=new JLabel("MiniGoogle",JLabel.CENTER);
      JLabel lab2=new JLabel("Select Files:",JLabel.CENTER);
      JLabel lab3=new JLabel("Enter Keywords",JLabel.CENTER);
      JPanel pane = new JPanel(new BorderLayout(0,50));
      JButton search = new JButton("Search!");
      JTextField kw=new JTextField(25);
      JButton Browse=new JButton("Browse");
      JFileChooser fc= new JFileChooser();
      ArrayList files=new ArrayList();
      String dest;

      home() // the frame constructor method
      {

        setBounds(100,100,350,350);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container con = this.getContentPane(); // inherit main frame
        con.add(pane);
        JPanel s=new JPanel(new FlowLayout());
        JPanel r=new JPanel(new FlowLayout());
        search.setActionCommand("search");
        r.add(lab2);
        r.add(Browse);
        r.add(lab3);
        r.add(kw);
        pane.add ("North", lab);
        pane.add ("Center", r);

        s.add(search);
        pane.add("South",s);
setVisible(true); // display this frame

Browse.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {


fc = new JFileChooser(); 
fc.setMultiSelectionEnabled(true);
fc.setCurrentDirectory(new java.io.File("C:/Ananya/Files/DSA/project 2/searchfiles"));
fc.setDialogTitle(dest);
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.setAcceptAllFileFilterUsed(false);
if (fc.showOpenDialog(fc) == JFileChooser.APPROVE_OPTION) { 
  files.addAll(Arrays.asList(fc.getSelectedFiles()));
  }
else {
  System.out.println("No Selection ");
  }
 }

});


 search.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e){
            String text=kw.getText();
                            if(text.equals("")||files==null)
                            {
                                JOptionPane.showMessageDialog(null,"Empty fields!","Error!",JOptionPane.WARNING_MESSAGE);
                            }
                            else
                            {
                                try{
                                    new Indexing(files,text);/*this is where the exception is thrown*/
                                    }catch(Exception ex)
                                   {
                                       System.out.println(ex+"home");
                                   }
                                }

                    }


    });
}


  public static void main(String args[])throws IOException {
  new home();

   }
  }

this is my indexing class:

public class Indexing{
HashMap map=new HashMap();
int n;
ArrayList temp;
String s;

public Indexing(ArrayList files,String kw)throws IOException
{
    for(int i=0;i<2;i++)
    {
        temp=new ArrayList(50);
    BufferedReader br = new BufferedReader(new FileReader((File)files.get(i)));
            String line = "", str = "";

            while ((line = br.readLine()) != null) {
                    str += line + " ";
            }
            StringTokenizer st = new StringTokenizer(str);
            while (st.hasMoreTokens()) {
                temp=new ArrayList(50);
                    s = st.nextToken();
                    s.trim();
                    s.toLowerCase();
                    char ch=s.charAt(s.length()-1);
                    if(!(Character.isLetterOrDigit(ch)))
                    s=s.substring(0,s.length()-1);

                    if(map.get(s)==null)
                    {
                        temp.add(files.get(i));
                        map.put开发者_如何学编程(s,temp);
                    }
                    else if(!(((ArrayList)map.get(s)).contains(files.get(i))))
                    {
                        ((ArrayList)map.get(s)).add(files.get(i));
                    }
            }
}
    ArrayList result=(ArrayList)map.get(kw);
    new SearchResults(result,kw);    //line 43 
}




}

this is the SearchResults class:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;

public class SearchResults {
    JFrame jtfMainFrame;
JLabel msg;
JPanel p;
    JPanel s;
    File fl;
    JButton buttons[];
    JLabel files[];
public SearchResults(ArrayList results,String kw) {
            jtfMainFrame = new JFrame(kw+" - MiniGoogle Search");
    jtfMainFrame.setSize(50, 50);
            p=new JPanel(new BorderLayout(0,60));
            msg=new JLabel(("Results for "+kw+":"),JLabel.CENTER);
            p.add("North",msg);
            s=new JPanel(new FlowLayout());
            int l=results.size();                //line 22
            for(int i=0;i<l;i++)
            {
                fl=(File)results.get(i);
                files[i].setText((i+1)+"."+ fl);
                buttons[i]=new JButton("Go!");
                s.add(files[i]);
                s.add(buttons[i]);
                buttons[i].addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e)
                    {
                        String[] commands = {"cmd", "/c",fl.getAbsolutePath()};
                        try{Runtime.getRuntime().exec(commands);}catch(Exception ex)
                        {
                            System.out.println(ex);
                        }

        }   
    });

            }
            p.add("Center",s);
            p.add("South",msg);
    jtfMainFrame.setBounds(100,100,350,350);    
    jtfMainFrame.setVisible(true);
}
public static void main(String[] args) {
    // Set the look and feel to Java Swing Look
    try {
        UIManager.setLookAndFeel(UIManager
                .getCrossPlatformLookAndFeelClassName());
    } catch (Exception e) {
                System.out.println(e);
    }

}    
}

this is the exception trace:

     java.lang.NullPointerException
at SearchResults.<init>(SearchResults.java:22)
at Indexing.<init>(Indexing.java:46)
at home$2.actionPerformed(home.java:75)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at   javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6041)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5806)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4413)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2440)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)


I'm pretty sure that the NPE occurs here in this line:

files.addAll(Arrays.asList(fc.getSelectedFiles()));

Check that fc.getSelectedFiles() does not return null.


It seems the exception occurs at this line:

fc.setDialogTitle(dest);

assign a value to dest first:

dest = "The Title!";


There seems to be a mistake in the mapping in class Indexing. In line 42 you fetch an ArrayList based on a key word kw. However the Map doesn't contain such a key word and returns null. SearchResult tries to call the size() method on that list and rightfully throws a NullPointerException.

We can't really fix your problem but that is the cause. Somewhere you need to either fix your mapping logic or add additional null checks. Whatever is appropriate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜