我不知道这段代码有什么问题。我的应用程序在运行时崩溃了。
以下是代码:
package com.example.smsTest;
import java.util.List;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Messages extends ListActivity {
Button btnNew;
private SQLiteAdapter mySQLiteAdapter;
private BroadcastReceiver mIntentReceiver;
ListView listview;
@Override
public void onCreate(Bundle savedInstanceState) {
btnNew = (Button) findViewById(R.id.btnNew);
super.onCreate(savedInstanceState);
setContentView(R.layout.messages);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
List<Message> values = mySQLiteAdapter.getAllMessages();
ArrayAdapter<Message> adapter = new ArrayAdapter<Message>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
btnNew.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(Messages.this,
SMSTest.class);
startActivity(myIntent);
}
});
}
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter("SmsMessage.intent.MAIN");
mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
@SuppressWarnings("unchecked")
ArrayAdapter<Message> adapter = (ArrayAdapter<Message>) getListAdapter();
Message message = null;
String msg = intent.getStringExtra("get_msg");
// Process the sms format and extract body & phoneNumber
msg = msg.replace("\n", "");
String body = msg.substring(msg.lastIndexOf(":") + 1,
msg.length());
String sender = msg.substring(0, msg.lastIndexOf(":"));
message = mySQLiteAdapter.createMessage(sender, body);
//adapter.add(message);
adapter.notifyDataSetChanged();
}
};
this.registerReceiver(mIntentReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(this.mIntentReceiver);
}
}
这是我刚添加的代码加上声明上面按钮的变量:
btnNew.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(Messages.this,
SMSTest.class);
startActivity(myIntent);
}
});
答案 0 :(得分:2)
您必须在使用LayoutInflater
或通过调用setContentView(R.layout.messages);
修改
btnNew = (Button) findViewById(R.id.btnNew);
super.onCreate(savedInstanceState);
setContentView(R.layout.messages);
到
super.onCreate(savedInstanceState);
setContentView(R.layout.messages);
btnNew = (Button) findViewById(R.id.btnNew);