所以我检查了R.id.button(我的按钮ID的名称),以确保它是好的,但是每当我尝试运行点击按钮时,它就会吓坏了,Log Cat告诉我我已经得到一个空指针异常。任何帮助将不胜感激,代码如下。
public class RSSReaderActivity extends Activity {
RSSParser RSStext;
public EditText url;
Button feedButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
url = (EditText) findViewById(R.id.url_text);
feedButton = (Button) findViewById(R.id.button);
setContentView(R.layout.main);
}
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;//true makes visible
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.exit: this.finish();
}
return true;//true makes visible
}
public void parser(View view){//test code
if(url.equals(null)){ //This is the line where my error is thrown according to log cat
Toast toast = Toast.makeText(getApplicationContext(), "No URL entered!", 5);
toast.show();
}
else{
String temp = url.toString();
RSStext = new RSSParser(temp);
}
}
}
我的主要类的XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center|top"
android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:text="@string/hello" />
<EditText
android:id="@+id/url_text"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clickable="true"
android:inputType="textUri"
android:text="@string/default_url" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:onClick="parser"
android:text="@string/feed_button" />
</LinearLayout>
答案 0 :(得分:4)
您必须在获取EditText之前设置contentview
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
url = (EditText) findViewById(R.id.url_text);
feedButton = (Button) findViewById(R.id.button);
}