【问题标题】:Android application crashes at launch whenever I attach an onclicklistener to a button每当我将 onclicklistener 附加到按钮时,Android 应用程序在启动时崩溃
【发布时间】:2011-04-01 21:45:21
【问题描述】:

大家好。我正在编写一个应用程序来检索最近的 fm 专辑,每当我将 onclicklistener 附加到在 search_layout.xml 中创建的按钮时,它都会在启动时崩溃。如果我注释掉监听器,它不会崩溃。代码如下:

public class SearchActivity extends Activity{

//data members
private EditText movieName;
private Button okayBut;
private Button cancelBut;
private URL url;
private InputStream in;
private TextView tv;
private LastFMAlbumHandler lfmah;
private Vector<String> parsedVector;
private String picUrlString;
private URL picUrl;
private SearchActivity search;
private RelativeLayout layout;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //initalize variables below
    movieName = (EditText) findViewById(R.id.entry);        
    okayBut = (Button) findViewById(R.id.ok);
    cancelBut = (Button) findViewById(R.id.cancel);
    layout = (RelativeLayout) findViewById(R.id.layout);
    search = this;



 this.okayBut.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
//      
            try{
//                      url = new URL("http://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&artist=cher&api_key=b25b959554ed76058ac220b7b2e0a026");
//                      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//                      in = conn.getInputStream(); //now  global variable, was bufferedInputStream
//                      try{
//                          lfmah = new LastFMAlbumHandler(tv);
//                          parseToHandler(in, lfmah);
//                          parsedVector = lfmah.getResults();
//                          for(int i = 0; i < parsedVector.size(); i++)
//                          {
//                              picUrlString = parsedVector.get(i);
//                              picUrl = new URL(picUrlString);
//                              imgGet imageGet = new imgGet(layout, picUrl, search);
//                              imageGet.run();
//                          }
//                      }
//                      catch (Exception e){
//                          //fresh.append("couldn't parse");
//                      }
//                      finally{
//                          in.close();
//                      }
//                  }catch(Exception e){
//                      tv.append("could not connect");
//                  } 
            }
     });    
    setContentView(R.layout.search_layout);
}

//ParseToHandler method
private void parseToHandler(InputStream in, CheapHandler handler) throws IOException, ParserConfigurationException, SAXException
{
    try{
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser parser = spf.newSAXParser();
        parser.parse(in, handler);
    }
    catch (IOException e)
    {
        tv.append("first");
    }
    catch(ParserConfigurationException e)
    {
        tv.append("second");
    }
    catch (SAXException e)
    {
        tv.append("third");
    }
    catch (Exception e)
    {
        tv.append("unknown");
    }
}

}

这里是 XML 代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/layout"  xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">

<TextView android:id="@+id/label" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="Enter movie name below:" />

<EditText android:id="@+id/entry" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:background="@android:drawable/editbox_background"
    android:layout_below="@id/label" />

<Button android:id="@+id/ok" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:layout_below="@id/entry"
    android:layout_alignParentRight="true" android:layout_marginLeft="10dip"
    android:text="OK" />

<Button android:id="@+id/cancel" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:layout_toLeftOf="@id/ok"
    android:layout_alignTop="@id/ok" android:text="Cancel" />
</RelativeLayout>

我非常感谢任何帮助。谢谢

【问题讨论】:

    标签: android button crash android-layout


    【解决方案1】:

    您在调用 setContentView 之前将 onClickListener 分配给按钮,因此此时按钮将为“null”,即布局尚未膨胀。

    【讨论】:

      【解决方案2】:

      setContentView(R.layout.search_layout);不应该位于调用findViewById的代码之前吗?

      【讨论】:

        【解决方案3】:

        将调用移至setContentView,使其位于对findViewById 的任何调用之前。在您致电 setContentView 之前,将找不到这些 ID。

        此外,建立网络连接是一项耗时的操作。您不应该在单击处理程序(或事件线程上的任何位置)中执行此操作。将那部分代码移动到单独的线程并开始使用onClick() 来启动线程。请参阅here 了解更多信息。

        【讨论】:

          【解决方案4】:
          setContentView(R.layout.search_layout) 
          

          这应该先于你的

           //initalize variables below 
          movieName = (EditText) findViewById(R.id.entry);         
          okayBut = (Button) findViewById(R.id.ok); 
          cancelBut = (Button) findViewById(R.id.cancel); 
          layout = (RelativeLayout) findViewById(R.id.layout); 
          search = this; 
          

          您应该使用 AsyncTask 向服务器发出请求,因为在 Android Api Level 10 之后无法在主 UI 线程上发出数据请求

          【讨论】:

            【解决方案5】:

            为你的 onClickListener 和 Button 试试这个

            Button button = (Button)findViewById(R.id.btn_configup1);        
            button.setOnClickListener(this);
            
            public void onClick(View v) {
            }
            

            【讨论】:

              【解决方案6】:

              在调用任何findViewById 之前,您应该先调用setContentView(R.layout.search_layout);

              【讨论】:

                【解决方案7】:

                我发现在onStart 中添加监听器为我解决了null pointer 的问题。

                也许视图/片段直到现在 onCreate 之后才会膨胀...

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-06-05
                  • 1970-01-01
                  • 2020-10-15
                  • 2017-12-22
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多