java.lang.NullPointerException 问题

Posted

技术标签:

【中文标题】java.lang.NullPointerException 问题【英文标题】:java.lang.NullPointerException Issue 【发布时间】:2013-01-10 01:34:16 【问题描述】:

我意识到这通常是一个简单的问题,但我一直在查看本网站和其他网站上的其他类似问题,但无法修复代码,也无法准确查看错误来自何处。我的问题似乎是调用分配给按钮的 OnClickListener,但我又可能错了。我基本上是从另一个有效的应用程序中直接复制了这段代码(只做了很少的改动)。这个事实让我更加困惑。提前感谢您对这个相对简单的问题的帮助。

代码:

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update_activity);

    final Handler handler;
    handler = new Handler();

    final EditText getCustID = (EditText) findViewById(R.id.customer);
    final EditText custvar1 = (EditText) findViewById(R.id.var1);
    final EditText custvar2 = (EditText) findViewById(R.id.var2);
    final EditText custvar3 = (EditText) findViewById(R.id.var3);

    class sendGET implements Runnable
    
        private String url;

        public sendGET(String mUrl)
        
            url = mUrl;
        

        public void run()
        
            try
            
                //Declare HttpClient and HttpGet
                HttpClient client = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(url);

                //Run HttpGet
                client.execute(httpget);

             catch (ClientProtocolException e) 
                // TODO Auto-generated catch block
             catch (IOException e) 
                // TODO Auto-generated catch block
                e.printStackTrace();
            
        
    

    class getCustomerData implements Runnable
           
        public void run()
        
            try
            
                InputStream stream = null;
                XMLparser xmlParser = new XMLparser();
                List<Customer> customers = null;

                String parseUrl = URL + getCustID.getText().toString();

                try
                
                    stream = downloadUrl(parseUrl);
                    customers = xmlParser.parse(stream);
                
                finally
                
                    stream.close();
                

                final Customer data = customers.get(0);

                handler.post(new Runnable() 
                    public void run() 
                        custvar1.setText(String.valueOf(data.var1));
                        custvar2.setText(String.valueOf(data.var2));
                        custvar3.setText(String.valueOf(data.var3));
                    
                );
            
            catch (IOException e)
            
                //return getResources().getString(R.string.connection_error);
            
            catch (XmlPullParserException e)
            
                //return getResources().getString(R.string.xml_error);
            
        

        private Customer readCustomer(XmlPullParser parser) throws XmlPullParserException, IOException
        
            parser.require(XmlPullParser.START_TAG, null, "customer");
            String custID = null;
            String var1 = null;
            String var2 = null;
            String var3 = null;

            while(parser.next() != XmlPullParser.END_TAG)
            
                if (parser.getEventType() != XmlPullParser.START_TAG)
                
                    continue;
                
                String name = parser.getName();
                if (name.equals("CustID"))
                
                    custID = readCustID(parser);
                 else if (name.equals("custvar1"))
                
                    var1 = readVar1(parser);
                 else if (name.equals("custvar2"))
                
                    var2 = readVar2(parser);
                 else if (name.equals("custvar3"))
                
                    var3 = readVar3(parser);
                 else
                
                    skip(parser);
                

            
            return new Customer(custID, var1, var2, var3);
        

        private String readCustID(XmlPullParser parser) throws IOException, XmlPullParserException
        
            parser.require(XmlPullParser.START_TAG, null, "CustID");
            final String custID = readText(parser);
            parser.require(XmlPullParser.END_TAG, null, "CustID");
            return custID;
        

        private String readVar1(XmlPullParser parser) throws IOException, XmlPullParserException
        
            parser.require(XmlPullParser.START_TAG, null, "custvar1");
            String var1 = readText(parser);
            parser.require(XmlPullParser.END_TAG, null, "custvar1");
            return var1;
        

        private String readVar2(XmlPullParser parser) throws IOException, XmlPullParserException
        
            parser.require(XmlPullParser.START_TAG, null, "custvar2");
            String var2 = readText(parser);
            parser.require(XmlPullParser.END_TAG, null, "custvar2");
            return var2;
        

        private String readVar3(XmlPullParser parser) throws IOException, XmlPullParserException
        
            parser.require(XmlPullParser.START_TAG, null, "custvar3");
            String var3 = readText(parser);
            parser.require(XmlPullParser.END_TAG, null, "custvar3");
            return var3;
        

        private String readText(XmlPullParser parser) throws IOException, XmlPullParserException
        
            String result = "";
            if (parser.next() == XmlPullParser.TEXT)
            
                result = parser.getText();
                parser.nextTag();
            
            return result;
        

        private void skip(XmlPullParser parser) throws IOException, XmlPullParserException
        
            if (parser.getEventType() != XmlPullParser.START_TAG)
            
                throw new IllegalStateException();
            
            int depth = 1;
            while (depth != 0)
            
                switch (parser.next()) 
                case XmlPullParser.END_TAG:
                    depth --;
                case XmlPullParser.START_TAG:
                    depth++;
                    break;
                
            
        

        class XMLparser
               
            public List<Customer> parse(InputStream in) throws XmlPullParserException, IOException 
                try
                
                    XmlPullParser parser = Xml.newPullParser();
                    parser.setInput(in, null);
                    parser.nextTag();
                    return readXML(parser);
                 finally 
                    in.close();
                
            

            private List<Customer> readXML(XmlPullParser parser) throws XmlPullParserException, IOException
            
                List<Customer> custData = new ArrayList<Customer>();

                parser.require(XmlPullParser.START_TAG, null, "xml");
                while (parser.next() != XmlPullParser.END_TAG)
                
                    if (parser.getEventType() != XmlPullParser.START_TAG)
                    
                        continue;
                    
                    String name = parser.getName();

                    //Look for customer tag
                    if (name.equals("customer"))
                    
                        custData.add(readCustomer(parser));
                    
                    else
                    
                        skip(parser);
                    
                

                return custData;
            
        

        private InputStream downloadUrl(String urlString) throws IOException
        
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);

            //start the query
            conn.connect();
            InputStream stream = conn.getInputStream();
            return stream;
        
    

    final Button getData = (Button) findViewById(R.id.getData);
    getData.setOnClickListener(new View.OnClickListener()
        public void onClick(View v)
        
            //Declare and start thread
            final Runnable mGetData = new getCustomerData();
            final Thread getData = new Thread(mGetData);
            getData.start();
        
    );

    final Button submit = (Button) findViewById(R.id.Submit);
    submit.setOnClickListener(new View.OnClickListener() 
        public void onClick(View v) 

            //set url
            String url = "**removed**";
            url += "var1=" + custvar1.getText().toString() + "&var2=" + custvar2.getText().toString() + "&var3=" + custvar3.getText().toString();

            //Declare and start thread
            final Runnable mConnect = new sendGET(url);
            final Thread Connect = new Thread(mConnect);
            Connect.start();
        
    );


public class Customer

    public final String custID;
    public final String var1;
    public final String var2;
    public final String var3;

    private Customer()
    
        custID = null;
        var1 = null;
        var2 = null;
        var3 = null;
    

    private Customer(String custID, String var1, String var2, String var3)
    
        this.custID = custID;
        this.var1 = var1;
        this.var2 = var2;
        this.var3 = var3;

    

Logcat 错误:

01-09 19:20:53.478: W/dalvikvm(911): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
01-09 19:20:53.478: E/androidRuntime(911): FATAL EXCEPTION: Thread-99
01-09 19:20:53.478: E/AndroidRuntime(911): java.lang.NullPointerException
01-09 19:20:53.478: E/AndroidRuntime(911):  at us.rns.editdata.UpdateActivity$1getCustomerData.run(UpdateActivity.java:90)
01-09 19:20:53.478: E/AndroidRuntime(911):  at java.lang.Thread.run(Thread.java:856)
01-09 19:20:54.408: W/IInputConnectionWrapper(911): showStatusIcon on inactive InputConnection

【问题讨论】:

这是在哪一行抛出异常? 停止使用“logcat 调试”。附加调试器。停止异常(当它被抛出时)。检查相关行上的表达式以找出哪个为空。 好像是抛出异常就行了:"stream.close();"如果我正确阅读调试器,但这对我来说更没有意义。 @Jim 这很有意义。您的 downloadUrl 方法失败,异常被捕获,此时 stream 仍然为空。 那么我猜这意味着尝试进行字符串连接会导致 URL 出现错误。听起来对吗? 【参考方案1】:

您的 downloadUrl 方法失败。

InputStream stream = null;
XMLparser xmlParser = new XMLparser();
List<Customer> customers = null;

String parseUrl = URL + getCustID.getText().toString();

try

    stream = downloadUrl(parseUrl);
    customers = xmlParser.parse(stream);

finally

    stream.close();

流对象设置为null,然后你分配stream = downloadUrl(parseUrl)

downloadUrl 方法失败,没有为stream 分配任何内容。

然后您尝试在finally 子句中关闭流。

private InputStream downloadUrl(String urlString) throws IOException

    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);

    //start the query
    conn.connect();
    InputStream stream = conn.getInputStream();
    return stream;

在这个方法上设置一个断点,并通过它进行调试。请返回它正在中断的确切行。我怀疑是conn.connect();InputStream stream = conn.getInputStream();

我也会在 finally 子句中这样做:

finally

    if(stream != null)
        stream.close();

也可以是:

您需要移动所有这些:

final EditText getCustID = (EditText) findViewById(R.id.customer);
final EditText custvar1 = (EditText) findViewById(R.id.var1);
final EditText custvar2 = (EditText) findViewById(R.id.var2);
final EditText custvar3 = (EditText) findViewById(R.id.var3);

final Button getData = (Button) findViewById(R.id.getData);

final Button submit = (Button) findViewById(R.id.Submit);

进入 onResume,而不是 onCreate()

【讨论】:

@A--C 最后两个是类中的静态字段,这会导致 NullRefException 因为它们没有被实例化(因为 View 还没有被绘制) 天哪,到处都是私人课程。我现在要逃跑了。 我目前没有 onResume 方法。那我应该创建一个吗?为什么这会对正在运行的代码产生影响? @Jim A--C 可能是对的,但我总是将我所有的 UI/可运行的东西放在 onResume 中,因为这是视图显示给用户之前的最后一步。 onResume 应该是什么样子的?

以上是关于java.lang.NullPointerException 问题的主要内容,如果未能解决你的问题,请参考以下文章

亲測,Eclipse报&quot;An error has occurred,See error log for more details. java.lang.NullPointerExce

来自 LayerDrawable 的异常

Microsoft Access 和 Java JDBC-ODBC 错误

如何使用其id获取单个SQLite行数据?