猿问

不使用按钮时,为什么新活动不会从此 OnClick 方法启动?

我在 Android Studio 中工作,并且正在使用回收器视图从数据库创建项目列表。在 RecyclerViewAdapter 中的 OnClick 函数中,我的目标是使用来自数据库的额外消息启动一个新活动(该函数可以正常工作并且在这种情况下不是问题)。当点击屏幕时,应用程序崩溃而不是加载新活动。

任何阻止应用程序崩溃的帮助将不胜感激。谢谢


翻翻过去那场雪
浏览 120回答 2
2回答

人到中年有点甜

两个最可能的问题是 (1)eventScreen活动未在您的 AndroidManifest.xml 中声明或 (2)context变量为空。要解决 (1),请将其添加到您的清单中:<activity&nbsp; &nbsp; android:name=".eventScreen"/>要解决 (2),请使用ContextViewHolder 的 itemView 中的保证非空:Context c = v.getContext();Log.d(TAG, eventName.get(position) + " clicked");Intent intent = new Intent(c, eventScreen.class);intent.putExtra("name", eventName.get(position));c.startActivity(intent);

智慧大石

您的数据库为空,因为您没有对其进行初始化。public class eventScreen extends AppCompatActivity {&nbsp; &nbsp; public Database db; // db is NULL&nbsp; &nbsp; public TextView name, location, date, website;&nbsp; &nbsp; @Override&nbsp; &nbsp; protected void onCreate(Bundle savedInstanceState) {&nbsp; &nbsp; &nbsp; &nbsp; super.onCreate(savedInstanceState);&nbsp; &nbsp; &nbsp; &nbsp; setContentView(R.layout.activity_event_screen);&nbsp; &nbsp; &nbsp; &nbsp; name = findViewById(R.id.name);&nbsp; &nbsp; &nbsp; &nbsp; location = findViewById(R.id.location);&nbsp; &nbsp; &nbsp; &nbsp; date = findViewById(R.id.date);&nbsp; &nbsp; &nbsp; &nbsp; website = findViewById(R.id.website);&nbsp; &nbsp; &nbsp; &nbsp; // You should initialize your DataBase db here before calling loadInfo()&nbsp; &nbsp; &nbsp; &nbsp; if (getIntent().hasExtra("name")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String eventName = getIntent().getStringExtra("name");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; loadInfo(eventName);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Toast.makeText(this, "No message", Toast.LENGTH_LONG).show();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public void loadInfo(String title){&nbsp; &nbsp; &nbsp; &nbsp; // db is still NULL&nbsp; &nbsp; &nbsp; &nbsp; // The crash happens here when you call --> db.getEventData() --> null.getEventData(title)&nbsp; &nbsp; &nbsp; &nbsp; String [] info = db.getEventData(title);&nbsp; &nbsp; &nbsp; &nbsp; name.setText("the ");&nbsp; &nbsp; &nbsp; &nbsp; location.setText("the");&nbsp; &nbsp; &nbsp; &nbsp; date.setText("the");&nbsp; &nbsp; &nbsp; &nbsp; website.setText("the");&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答